Search code examples
cfileiofwritefread

How do I read bytes from a file into strings and ints using C?


I wrote a file using C's fwrite where I wrote a string, followed by some ints, multiple times. I used this code to write:

fwrite(&words,sizeof(char),strlen(words) - 1, outputFile);
fwrite(&nextNum,sizeof(int),1, outputFile);

How can I read my file back into strings and ints?

Also, would it be faster to read an array of ints from the file instead of multiple consecutive ints?


Solution

  • The way you write into the file you lose a critical piece of information: the length of your string. There are generally three ways to handle this:

    1. (The least efficient!) Assume your strings are shorter than, say, 10 characters and always write 10 characters (padding with spaces as needed) and read back 10 characters, trimming the spaces. This is the "fixed-width" format.
    2. Prepend every string you write with the length information, say a 16-bit word (so you limit the size of your strings to 64K, which is adequate for most applications)
    3. Use an end-of-string indicator. The most obvious one being a '\0' null-terminator used for standard C-strings

    Of course, reading back would depend on the technique you chose to write the strings out. But once you are done with the string's variable length complication writing/reading integers (which are always of an exact, known size) should be a breeze.