将单词输入到文本文件中并显示(c语言)
从键盘输入10个英文单词到二维字符数组中,并保存到文本文件中(单词间以空格分隔,然后再从该文件中读出所有单词并显示到屏幕。
#include <stdio.h> #include <stdlib.h> #define N 2 void main(void) { FILE *fp; char a[N][80]={}; int i; if((fp = fopen("a.txt", "w")) == NULL){ printf("Can't Open File!"); exit(0); } printf("请输入%d个以空格分隔的单词:\n",N); for(i=0;i<N;i++){ scanf("%s",&a[i]); } if(!feof(fp)){ for(i=0;i<N;i++){ fprintf(fp,"%s\n",a[i]); } } fclose(fp); if((fp = fopen("a.txt", "r")) == NULL){ printf("Can't Open File!"); exit(0); } printf("显示文件中的单词:\n"); if(!feof(fp)) { for (i = 0; i <= N; i++) { if (EOF == fscanf(fp, "%s", &a[i])) break; printf("%s \n", a[i]); } } fclose(fp); }