Search code examples
cfopenfclose

C Programming. Using fopen fclose for text file operations


I am opening a text file and processing word count function to count words and closing a file. Next, I open the same file again and store it in the array with limit to word count value in an array.

Here, if I use fopen and fclose just once like in line 1 and 16, my program does not work. But if I open it (line 1) process it then close it (line 10) and open it again (line 12) for second process, my program works. Does it mean that fopen can only handle one process at a time and I have to open it again for second process?

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);

Solution

  • You can do whatever you want to the file while it is open.

    I suspect your problem is that you are reading to the end of the file in one set of operations and then you try and read the file again while you are at the end. Look for the rewind() function

    To rewind to the start of the file just call rewind(fptrr); after the first countwords. Alternately you can call fseek(fptrr, 0L, SEEK_SET) but rewind() is clearer.

    Note that closing the file and re-opening it automatically resets the file to read form the start which is why your new version works.