C Programming. Using fopen fclose for text file operations
我正在打开一个文本文件,并处理单词计数功能以对单词进行计数并关闭文件。
接下来,我再次打开同一文件,并将其存储在数组中,并限制数组中的字数值。
在这里,如果我像第1行和第16行一样使用fopen和fclose一次,则我的程序将无法运行。但是,如果我打开它(第1行),然后关闭它(第10行),然后再次打开它(第12行)以进行第二个过程,那么我的程序就可以工作。这是否意味着fopen一次只能处理一个进程,而我必须再次为第二个进程打开它?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); |
您可以在文件打开时对其执行任何操作。
我怀疑您的问题是您正在通过一组操作读取文件的结尾,然后尝试在结尾处再次读取文件。寻找rewind()函数
要倒退到文件的开头,只需在第一个计数字之后调用
请注意,关闭文件并重新打开会自动将文件重置为从开始读取,这就是您的新版本起作用的原因。