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?
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?
Like this:
Make sure that 'c' is an int, not a char. You will miss EOF otherwise.Code:int c; FILE *fp = fopen("filename", "rb"); while ((c = fgetc(fp)) != EOF) { /* ... */ } fclose(fp);
what if i am using specific fread statements within the loop
i.e.
where readfile is my file pointer.
what would go in the question marks?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; }
Code:!feof(readfile)
>!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.When fread returns fewer items than you asked for, it either reached the end of the file or encountered an error.Code:while ( 1 ) { if ( fread(&version, sizeof version, 1, readfile) < 1 ) { break; } /* ... */ }
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.*