标签:str int gets txt 读取 lib 指针 sys for
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> int getFilelen(FILE * file) { int len = 0; if (file == NULL) { return -1; } char buf[1024]; //读取每一行 while (fgets(buf, 1024, file) != NULL) { len++; } //设置光标 fseek(file, 0, SEEK_SET); return len; } //文件指针 长度 堆区数组 void readFileData(FILE * file, int len, char ** pArray) { if (file == NULL || len <= 0 || pArray == NULL) { return; } char buf[1024]; //读取每一行 int index = 0; while (fgets(buf, 1024, file) != NULL) { int currentlen = strlen(buf) + 1; char * currenP = (char *)malloc(sizeof(char) * currentlen); strcpy(currenP, buf); pArray[index++] = currenP; memset(buf, 0, 1024); } } void showFileData(char ** pArray, int len) { for (int i = 0; i < len; i++) { printf("第%d行内容:%s", i+1, pArray[i]); } } void freeSpace(char ** pArray, int len) { if (pArray == NULL || len == NULL) { return; } for (int i = 0; i < len; i++) { if (pArray[i] != NULL) { free(pArray[i]); pArray[i] = NULL; } } } void test01() { FILE * file = fopen("./test.txt", "r"); if (file == NULL) { printf("打开文件失败!\n"); return; } int len = getFilelen(file); char ** pArray = (char **)malloc(sizeof(char *) * len); readFileData(file, len, pArray); showFileData(pArray, len); freeSpace(pArray, len); pArray = NULL; } void main() { test01(); putchar(‘\n‘); system("pause"); }
标签:str int gets txt 读取 lib 指针 sys for
原文地址:https://www.cnblogs.com/seraphgabriel/p/9372083.html