I have a file with multiple strings, each string on a separate line. All strings are 32 character long (so 33 with the '\n' at the end).
I am trying to read all the strings. For now, I just want to read them and not store them as follows:
char line[32];
while (!feof(fp)) {
fgets(line, 32, fp);
}
printf("%s", line);
This prints out zero. Why isn't it working?
Furthermore, I am trying to store a null terminator at the end of each string read. I changed the line array to length 33 but how would I make it that if '\n' is found, replace it with \0 and store that?
You code isn't working because you are only allocating space for lines of 30 characters plus a newline and a null terminator, and because you are only printing out one line after feof() returns true.
Additionally, feof() returns true only after you have tried and failed to read past the end of file. This means that while (!feof(fp)) is generally incorrect - you should simply read until the reading function fails - at that point you can use feof() / ferror() to distinguish between end-of-file and other types of failures (if you need to). So, you code could look like:
char line[34];
while (fgets(line, 34, fp) != NULL) {
printf("%s", line);
}
If you wish to find the first '\n' character in line, and replace it with '\0', you can use strchr() from <string.h>:
char *p;
p = strchr(line, '\n');
if (p != NULL)
*p = '\0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With