Search code examples
cfunctioneoffile-read

How to take first row from this list of text?


I have a list of columns containing text but I just to fetch first upper row from this list. How to do that?

#include <stdio.h>

int main()
{
  FILE *fr;
  char c;
  fr = fopen("prog.txt", "r");
  while( c != EOF)
  {
    c = fgetc(fr); /* read from file*/
    printf("%c",c); /*  display on screen*/
  }
  fclose(fr);
  return 0;
}

Solution

  • Your stop condition is EOF, everything will be read to the end of the file, what you need is to read till newline character is found, furthermore EOF (-1) should be compared with int type.

    You'll need something like:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
      FILE *fr;
      int c;
    
      if(!(fr = fopen("prog.txt", "r"))){ //check file opening
        perror("File error");
        return EXIT_FAILURE; 
      }
    
      while ((c = fgetc(fr)) != EOF && c != '\n')
      {
        printf("%c",c); /*  display on screen*/
      }
      fclose(fr);
      return EXIT_SUCCESS;
    }
    

    This is respecting your code reading the line char by char, you also have the library functions that allow you to read whole line, like fgets() for a portable piece of code, or getline() if you are not on Windows, alternatively download a portable version, and, of course you can make your own like this one or this one.