在上文介绍了C中文件操作的一些基本函数,下面给一个简单例子,完成从控制台输入一段字符串,然后将其写入文件,然后从文件中读出刚刚写入的内容,代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> const int LENGTH=80; int main(void){ char mystr[LENGTH]; int lstr=0; int mychar=0; FILE * pfile=NULL; char *filename="C:\\temp\\test.txt"; printf("\nEnter an interesting string of less than 80 characters:\n"); fgets(mystr,LENGTH,stdin); if(!(pfile=fopen(filename,"w"))) { printf("Fail to open"); exit(1); } lstr=strlen(mystr); for(int i=0;i<lstr;i++){ fputc(mystr[i],pfile); } fclose(pfile); if(!(pfile=fopen(filename,"r"))) { printf("Fail to open"); exit(1); } printf("This is the content of your interesting string:\n"); while((mychar=fgetc(pfile))!=EOF) putchar(mychar); putchar('\n'); fclose(pfile); // remove(filename); return 0; }
原文地址:http://blog.csdn.net/u010142437/article/details/28422535