Let's say I want to read a file where each line has a string, and when there is a new line or the end of the file, I print the number of characters read. For example,
abcdf
asd
sdfsd
aa
This would print (counting new line characters at the end of each string):
10
8
(there is no new line at the end of the last line, so we get 8 instead of 9). I could do something like this
FILE* f;
// ...
int charCount = 0;
char line[20];
while (fgets(line, sizeof line, f))
{
if (strcmp(line, "\n") == 0)
{
printf("%d\n", charCount);
charCount = 0;
}
else
{
charCount += strlen(line);
}
}
printf("%d\n", charCount);
Notice that I have to repeat the printf after the loop ends, because if I don't, I wouldn't print the last value (because the file reached the end and there is not a new line at the end). For a printf
, this is not that bad, but if I had something more complicated, it would result in a lot of repeated code. My workaround is putting what I want inside a function and just call the function after the loop, but I feel like there has to be a better way. Is there a better way to parse through a file like this? Preferably not character by character in case I have some formatted data that I need to use fscanf
with.