You can simply use:
char buffer[4096]; size_t nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp); if (nbytes == 0) ...EOF or other error... else ...process nbytes of data...
Or, in other words, provide yourself with a data space large enough for any valid data, and then write down how much data was actually read in the line. Note that a line will not have a null end, unless buffer
contained all zeros before fread()
or the file contained null bytes. You cannot rely on a local variable to be nullified before use.
It is unclear how you want to create a “corresponding size variable”. You can use dynamic memory allocation ( malloc()
) to provide the correct amount of space, and then return the selected item from this function. Remember to check for zero return (from memory) before using it.
source share