C编程.使用fopen fclose进行文本文件操作

SON*_*ONI 1 c fopen fclose

我打开一个文本文件并处理字数统计功能来计算单词和关闭文件.接下来,我再次打开相同的文件并将其存储在数组中,并限制数组中的字数值.

在这里,如果我在第1行和第16行使用fopen和fclose一次,我的程序不起作用.但是如果我打开它(第1行)处理它然后关闭它(第10行)并再次打开它(第12行)进行第二个处理,我的程序可以工作.这是否意味着fopen一次只能处理一个进程,我必须再次打开它进行第二个进程?

1. fptrr = fopen(fname,"r"); // open the text file in read mode
2. 
3.  if (fptrr == NULL) {//if file name does not match
4.       printf("Error: No such file or directory");
5.       return -1;
6.     }
7. 
8. wordCount += countWords(fptrr); //run word count function and get the value of total words
9. 
10. fclose(fptrr); // close the file
11. 
12. fptrr = fopen(fname,"r");
13. for(int i=0;i<wordCount;i++){ // define size of loop equal to words in a file
14.    fscanf(fptrr, "%s", fileArray[i]); //scan and store in array
15. }
16. fclose(fptrr);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ett 5

您可以在文件打开时对文件执行任何操作.

我怀疑你的问题是你在一组操作中读到文件的末尾,然后你在最后时尝试再次读取文件.寻找rewind()函数

rewind(fptrr);回放到文件的开头,只需在第一个计数字后调用.或者你可以打电话fseek(fptrr, 0L, SEEK_SET)但倒带()更清晰.

请注意,关闭文件并重新打开它会自动重置文件以从开始处读取,这就是新版本的工作原因.