C语言文件——字符串的方式读出与写入
conclusion:
the steps of wirte into filethe follow code you can validate above contents directly.
//C语言按字符串写入文件 #include<stdio.h>#include<stdlib.h>#include<string.h>#define maxn 1024int main(){//C语言按字符串写入文件 /* steps:1.定义文件路径和文件操作2.定义文件指针以及存储变量3.打开文件(无出错处理) 4.读入所需的内容(输入-1代表结束)5.关闭文件 *///1.char *str=(char*)malloc(sizeof(char)*maxn);char *source="test2.txt";//2.char *op="w+t";FILE *fp=NULL;//3.fp=fopen(source,op);//4.puts("请输入信息:");while(1){if(strcmp(gets(str),"-1")==0) break;strcat(str,"\n");fputs(str,fp);} if(ferror(fp)) puts("文件写入错误!");//5.fclose(fp);return 0;}
the steps of read from filehurry to make it come true by yourself and validate it !follows are code
//C语言字符串读出或写入文件 #include<stdio.h>#include<stdlib.h>#define maxn 1024int main(){//读出文件 /* steps: 1.定义文件路径和文件操作2.定义文件指针以及存储变量3.打开文件(出错处理)4.读出文件的内容5.关闭文件 *///1.char *str=(char*)malloc(sizeof(char)*maxn);char *source="test.txt";//2.char *op="r+t";FILE *fp=NULL;//3.fp=fopen(source,op);if(fp==NULL){puts("文件打开失败!");exit(0);}//4.while(fgets(str,maxn,fp)!=NULL){puts(str);}if(ferror(fp)) {puts("文件读取过程发生错误!");}//5.fclose(fp);return 0;}
Please remember that every night you have stayied up and the path you have passed are always glittering !Cheer on ! The student who spare no effort on preparing for the examination for graduate school !
/6/4