#include
#include
#include
typedef struct _info* pInfo;
struct _info
{
int line;
int len;
char data[0];
}info;
int getFileLine(FILE* fd)
{
if (fd == NULL)
{
fprintf(stdout, "[%s]%d : get file line failed\r\n", __FILE__,__LINE__);
return -1;
}
int num = 0;
char buf[1024];
while ((fgets(buf, 1024, fd)) != NULL)
{
num++;
}
// 注意文件指针的问题, 避免在计算文件的内容行数的时候, 计算为空.
fseek(fd, 0, 0);
return num;
}
int readFile(FILE *fd, int len, pInfo* pArray)
{
if (fd == NULL || pArray == NULL || len <= 0)
{
return -1;
}
char buf[1024];
int line_len =0;
int index = 0;
memset(buf, 0, 1024);
while ((fgets(buf, 1024, fd)) != NULL)
{
int currentLen = 0;
currentLen = strlen(buf) + 1;
pInfo currentP = malloc(sizeof(info) + currentLen);
currentP->len = strlen(buf);
currentP->line = index;
strcpy(currentP->data, buf);
// append to pArray;
pArray[index] = currentP;
index++;
memset(buf, 0, 1024);
}
return 1;
}
void printFile(pInfo* pArray,int len)
{
if (pArray == NULL)
{
return NULL;
}
pInfo current = NULL;
for (int i = 0; i < len; i++)
{
current = pArray[i];
fprintf(stdout, " current %d line,current string len is:%d, current string is : %s", current->line,current->len,current->data);
}
}
void freeNode(pInfo* pArray, int len)
{
if(pArray == NULL || len < 0)
{
return NULL;
}
for (int i=0;i
{
free(pArray[i]);
pArray[i] = NULL;
}
free(pArray);
pArray = NULL;
}
void test(const char* filename)
{
if (filename == NULL)
{
return NULL;
}
FILE *fd = NULL;
fd = fopen(filename,"r");
if (fd == NULL)
{
return NULL;
}
int len = getFileLine(fd);
if (len == -1)
{
return NULL;
}
pInfo* pArray = malloc(sizeof(pInfo)*len);
if (pArray == NULL)
{
fprintf(stdout, "[%s]%d : malloc parray failed \r\n", __FILE__, __LINE__);
return NULL;
}
int res = readFile(fd, len, pArray);
if (res == -1)
{
fprintf(stdout, "[%s]%d : read file failed \r\n", __FILE__, __LINE__);
return NULL;
}
// print;
printFile(pArray, len);
freeNode(pArray,len);
pArray = NULL;
if (pArray != NULL)
{
perror("parray is't empty\r\n");
}
else {
perror("parray is empty\r\n");
}
}
int main()
{
const char* file = "./ReadMe.txt";
test(file);
return 0;
}
存在问题 :
如果读取的文件时中文时, 在console中输出是乱码.