I'm new at programming so there are some basics and maybe common sense that I don't know. I have a question about how to use fgets right. Based on the explanation of fgets, it seems that fgets should stop whenever it reads n-1 characters, hit the EOF or hit a newline character. For example, I create a text file like below:
red 100
yellow 400
blue 300
green 500
purple 1000
...
The color and the integer is separated by a tab. When I create this text file, I need to hit enter at the end of each line to start a new line. In this case, hitting enter equals to add a newline character, '\n', is that right?
If it is right that there is a '\n' at the end of each line, I run the fgets code as below:
fgets(string, 100, fp);
Since the characters contain in each line is much less than 100, the fgets should hit the newline character before reach the maxlength limit and it should stop and return a NULL. Is that correct?
If my understanding above are not right, there is no '\n' at the end of each line, or fgets does not stop at the end of each line, what is the number of maxlength (i.e., the N in the fgets(string, N, stream) function) should I pick to make sure that the file input properly due to my ultimate goal is to parsing each line and store each line into a structure. By the way, there are 100 lines in the file.
n
infgets
is the number of bytes length of the buffer. If that limit is reached before the EOL in the file, then nonewline
will be at the end of the input string, and the next call tofgets
will continue from the same place in the file. But the question is a muddle. Output is not input. – Weather Vanemy_favorite_input_function()
allows outside agents to overwhelm system resources. Pick a largen
- suggest twice as large as suggested by the programs needs:#define LINE_SIZE 1000
or 80 or 8675309 and deem any input where(strlen(buffer) >== LINE_SIZE - 1)
is true as nefarious and exit with a failure. – chux - Reinstate Monica