I’m using C and I want to read from a binaryFile.
I know that it is contain strings in the following way: Length of a string, the string itself, the length of a string, string itself, and so on…
I want to count the number of times which the string Str appears in the binary file.
So I want to do something like this:
int N;
while (!feof(file)){
if (fread(&N, sizeof(int), 1, file)==1)
...
Now I need to get the string itself. I know it’s length. Should I do a ‘for’
loop and get with fgetc char by char? I know I’m not allowed to use fscanf since
it’s not a text file, but can I use fgetc? And would I get what I’m expecting for
my string? (To use dynamic allocation for char* for it with the size of the length
and use strcpy to add it to the current string?)
You should probably loop on:
You could use
getc()orfgetc()in a loop; that would work. However, the directfread()is much simpler (and is coded as if it usesgetc()in a loop).You might want to do some sanity checking on
Nbefore blindly using it withmalloc(). In particular, negative values are likely to lead to much unhappiness.The file format as written is tied to one class of machine — either big-endian or little-endian, and with the fixed size of
int(probably 32-bits). Writing more portable data is slightly fiddlier, but eminently doable — but probably not relevant to you just yet.Using
feof()is seldom the correct way to test for whether to continue with a loop. Indeed, there is not often a need to usefeof()in code. When it is used, it is because an I/O operation ‘failed’ and you need to disambiguate between ‘it was not an error — just EOF’ and ‘there was some sort of error on the device’.