Reading a line from a file in C

I have a file with several lines, each line in a separate line. All lines are 32 characters long (therefore 33 with the "\ n" character at the end).

I am trying to read all the lines. For now, I just want to read them, and not store them like this:

char line[32]; while (!feof(fp)) { fgets(line, 32, fp); } printf("%s", line); 

Prints zero. Why doesn't it work?

Also, I'm trying to keep a null terminator at the end of every line I read. I changed the line array to a length of 33 , but how would I do it if '\n' , replace it with \0 and save it?

+4
source share
3 answers

The code does not work because you allocate space for lines of 30 characters plus a newline and null terminator, and because you only print one line after feof() returns true.

In addition, feof() returns true only after you tried and could not read the end of the file. This means that while (!feof(fp)) is usually incorrect - you just have to read until the read function works - at this point you can use feof() / ferror() to distinguish between end errors file and other types (if you need to). So the code might look like this:

 char line[34]; while (fgets(line, 34, fp) != NULL) { printf("%s", line); } 

If you want to find the first character '\n' 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'; 
+5
source

Here is a basic approach:

 // create an line array of length 33 (32 characters plus space for the terminating \0) char line[33]; // read the lines from the file while (!feof(fp)) { // put the first 32 characters of the line into 'line' fgets(line, 32, fp); // put a '\0' at the end to terminate the string line[32] = '\0'; // print the result printf("%s\n", line); } 
+1
source

It looks something like this:

 char str[33]; //Remember the NULL terminator while(!feof(fp)) { fgets(str, 33, fp); printf("%s\n",str); } 
0
source

Source: https://habr.com/ru/post/1381208/


All Articles