《 1 》
#include<stdio.h> int main() { FILE *fpin, *fpout; char ch; if((fpin=fopen("d:\c1.txt", "wt"))==NULL) { printf("Cannot open file strike any key exit!"); return 0; } ch = getchar(); while(ch!=' ') { fputc(ch, fpin); ch = getchar(); } fclose(fpin); if((fpout = fopen("d:\c1.txt", "rt")) == NULL) { printf(" Cannot open file "); return 0; } ch = fgetc(fpout); while(~ch) { putchar(ch); ch = fgetc(fpout); } printf(" "); fclose(fpout); }
《 2 》
读字符串函数(fgets)
格式:fgets(字符数组名, n, 字符指针)
功能:从指定的文件中读入一个字符串存入字符数组中。
说明:n表示从文件中读出的字符串不超过 n-1 个字符,在读入的最后一个字符后自动加上字符串结束标志 ' ' 。
#include<stdio.h> int main() { FILE *fp; char str[11]; if((fp = fopen("c:\c1.txt", "rt"))==NULL) { printf(" Cannot open file strike any key!"); return 0; } fgets(str, 11, fp);//从fp所指的文件中读出n-1个字符存入字符数组str中。 printf("%s ", str); fclose(fp); return 0; }