I am using fgetc to read a string from a file. As i dont know how long the string will be i need to reallocate space for the array that should hold the data. For that I need to know when the current array is full. I am not quite sure if the char array is null terminated after reading a character. So for example i have an array of size 8 and fgetc is going to give me the 9th char. Is the size of the array now 8 or 9? (8 chars + \0 or only the 8 chars). Is there a way to test it? And if there is no \0. Do I need to add it by myself to the char array when i finished reading in the string?
3 Answers
You need to keep track of both the current size of the buffer, and the position where you add characters. then if the position is equal to the size you need to increase the buffer. The actual size should be +1 to accommodate the terminating \0 character, which you must always add after the last character read.
Comments
When you use fgetc you are building the memory which holds the string byte by byte, so you need to have your memory allocation be total string length + 1 because you want the extra byte for the termination character '\0'.
The functions that work with "string" are really looking at a collections of bytes ending with '\0'. So for example "Hello World" is stored as 'H' 'e' 'l' 'l' 'o' 'W' 'o' 'r' 'l' 'd' '\0' in memory; and that's how functions know when to STOP processing a string.