Thread: read until end of file

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    88

    read until end of file

    is there a way to read from a binary file until you reach the end of the file? If so how could this be done?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    62
    Like this:

    Code:
    int c;
    FILE *fp = fopen("filename", "rb");
    
    while ((c = fgetc(fp)) != EOF) {
      /* ... */
    }
    
    fclose(fp);
    Make sure that 'c' is an int, not a char. You will miss EOF otherwise.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    what if i am using specific fread statements within the loop

    i.e.
    where readfile is my file pointer.
    Code:
    while(??????????????){
    fread(&version, sizeof (short), 1, readfile);	
    			data_ptr[file_count].version = version;
    			fread(&bit_flag, sizeof (short), 1, readfile);
    			data_ptr[file_count].bit_flag = bit_flag;
    			fread(&method, sizeof (short), 1, readfile);
    			data_ptr[file_count].method = method;
    			fread(&mod_time, sizeof (short), 1, readfile);
    			data_ptr[file_count].mod_time = mod_time;
    			fread(&mod_date, sizeof (short), 1, readfile);
    			data_ptr[file_count].mod_date = mod_date;
    			fread(&crc_32, sizeof (int), 1, readfile);
    			data_ptr[file_count].crc_32 = crc_32;
    }
    what would go in the question marks?

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    62
    Code:
    !feof(readfile)

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >!feof(readfile)

    FAQ > Explanations of... > Why it's bad to use feof() to control a loop

    >what would go in the question marks?

    You might try something like this.
    Code:
    while ( 1 )
    {
       if ( fread(&version, sizeof version, 1, readfile) < 1 )
       {
          break;
       }
       /* ... */
    }
    When fread returns fewer items than you asked for, it either reached the end of the file or encountered an error.
    Last edited by Dave_Sinkula; 10-13-2003 at 06:29 PM.
    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.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM