Thread: how these file operations work?

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    99

    how these file operations work?

    I have a question about the following code. I would like to know how the marked places work, I mean what is happening there.
    I have a file, called info.dat, with some lines written by another program. This following code displays the contents of the file, and separates each line with a vertical tab.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX 100
    
    FILE *fp;
    
    int main()
    {
       char data[MAX];
      
       if( (fp = fopen("info.dat", "r")) == NULL )
       {
          printf("This file does not exist!");
          exit(0);
       }
       else
       {
          printf("First N: Last N: GPA\n\n");
          fgets(data, MAX, fp); /* does it read the whole file??? */
          while( !(foef(fp)) )
          {
             printf("%s\v", data); /* prints one line, how? */
             fgets(data, MAX, fp); /* huh? */
          }		 
       
       fclose(fp);
        }
       
       return 0;
    }
    I would appreciate if someone could enlighten me how it works.
    Thanks.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    99
    So, it reads one line at a time? And if I have a multiline file, e.g
    blah bla 5.3
    blah bla 3.7
    blah vla 2.6
    I need to put it in a while loop to read till the end of file? Is that right?

  4. #4
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    fgets() terminates when it encounters a newline character, so if you wanted to go through the whole file you would do something like this:

    Code:
    while(fgets(data,MAX,fp) != NULL)
    {
        /* Do whatever */
    }
    Why do we check for NULL? Because fgets() returns a NULL whenever it encounters EOF or encounters an error.
    The cost of software maintenance increases with the square of the programmer's creativity.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File being filled with NULLs
    By Tigers! in forum Windows Programming
    Replies: 2
    Last Post: 06-30-2009, 05:28 PM
  2. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. The Bludstayne Open Works License
    By frenchfry164 in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 11-26-2003, 11:05 AM