【发布时间】:2023-04-08 06:02:02
【问题描述】:
我正在打开一个文本文件并处理字数统计功能来计算字数并关闭一个文件。 接下来,我再次打开同一个文件并将其存储在数组中,限制为数组中的字数值。
在这里,如果我像第 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);
【问题讨论】:
-
countWords()的定义在哪里? -
第一次通读文件后,您应该使用
fseek返回文件开头再次处理它。你关于 fopen 只处理一个进程的问题,我觉得很困惑。你能澄清一下吗? -
或使用rewind。
-
@BLUEPIXY 谢谢,现在可以使用了。