簡體   English   中英

C編程。 使用fopen fclose進行文本文件操作

[英]C Programming. Using fopen fclose for text file operations

我正在打開一個文本文件並處理單詞計數功能以對單詞進行計數並關閉文件。 接下來,我再次打開相同的文件,並將其存儲在數組中,並限制數組中的字數值。

在這里,如果像第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);

打開文件后,您可以對其執行任何操作。

我懷疑您的問題是您正在通過一組操作讀取文件的末尾,然后嘗試在末尾再次讀取文件。 尋找rewind()函數

要倒退到文件的開頭,只需調用rewind(fptrr); 在第一個字詞之后。 您也可以調用fseek(fptrr, 0L, SEEK_SET)但rewind()更清晰。

請注意,關閉文件然后重新打開會自動將文件重置為從頭開始讀取,這就是您的新版本起作用的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM