#include <stdio.h> #include <stdlib.h> #include <string.h> 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<len;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; }
存在問題 :app
若是讀取的文件時中文時, 在console中輸出是亂碼.指針