标签:
//fputs()和fgets() #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //文本写文件 int writeWord(const char *path,const char *pword){ int ERRO_MSG = 0; if (path == NULL) { ERRO_MSG = 1; printf("path==NULL erro msg:%d\n", ERRO_MSG); return ERRO_MSG; } if (pword == NULL) { ERRO_MSG = 2; printf("pword==NULL erro msg:%d\n", ERRO_MSG); return ERRO_MSG; } //定义文件指针 FILE *fpw=NULL; //打开文件 fpw = fopen(path, "w");//w 打开只写文件,若文件存在,则文件长度清零,即文件内容会消失,若文件不存在则建立该文件 //判断文件是否打开成功 if (fpw==NULL) { ERRO_MSG = 1; printf("文件打开失败 fpw==NULL erro msg:%d\n", ERRO_MSG); return ERRO_MSG; } //开始写文件 fputs(pword, fpw); //关闭文件 if (fpw!=NULL) { fclose(fpw); } return ERRO_MSG; } //文件读文件 char ** readtxt(const char *path)//二级指针做输出 { int ERRO_MSG = 0; if (path==NULL) { ERRO_MSG = 1; printf("path==NULL erro msg:%d\n", ERRO_MSG); //return ERRO_MSG; } //定义文件指针 FILE *pfr = NULL; //打开文件 pfr = fopen(path, "r"); if (pfr==NULL) { ERRO_MSG = 3; printf("pfr==NULL erro msg:%d,文件路径:%s\n", ERRO_MSG, path); //return ERRO_MSG; } //开始读文件 //1.定义文件缓存数组 char bufarr[100] = { 0 }; //2.0 获取文本具体行数 //2.1 定义临时变量 int index = 0; //2.0定义返回二维数组 char **resbuf = (char **)malloc(sizeof(char *)*(index+2)); //读文件 while (!feof(pfr)){//feof()如果文件结束,则返回非0值,否则返回0 memset(bufarr, 0, sizeof(char)*100); fgets(bufarr, 100, pfr); char *bufstr1 = (char *)malloc((sizeof(char)*strlen(bufarr)+1)); //拷贝字符串 strcpy(bufstr1, bufarr); resbuf[index] = bufstr1; index++; resbuf = (char **)realloc(resbuf, sizeof(char *)*(index + 2)); } resbuf[index] = NULL; return resbuf; } void main(){ //定义文件路径 char *path = "E:\\Test\\CwordTest\\";//只适用于window char *path1 = "E:/Test/CwordTest/a1.txt"; writeWord(path1, "asfasdfasdgafdsgadf\r\nsdgagasdfgsdfg\r\ndsafgshfetgrhet"); char **pdata = NULL; pdata=readtxt(path1); int index = 0; if (pdata!=NULL) { while (pdata[index] != NULL){ printf("%s\n", pdata[index]); //释放内存 free(pdata[index]); pdata[index] = NULL; index++; } free(pdata); pdata = NULL; } system("pause"); }
标签:
原文地址:http://www.cnblogs.com/zhanggaofeng/p/5450027.html