5

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?

1
  • 1
    all the standard string function rely one the NULL character being there, so yes you have to add it or you are going to run in strange issues Commented Oct 25, 2011 at 13:22

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

since fgetc reads a one character per call, to get size of a string, you should check read character to be a \0 or EOF reached. if you see a \0 byte, you should copy all the bytes including \0. if EOF is reached without a \0 and if character counter is > 0, you should add a \0 yourself.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.