1

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;
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53

3 Answers3

5

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
2

just replace EOF as '\n'(new line char). Than your code will read until reaching the new line. Here is what it looks like:

#include <stdio.h>
int main()
{
  FILE *fr;
  char c = ' ';
  fr = fopen("prog.txt", "r");
  while(c != EOF && c != '\n')
  {
    c = fgetc(fr); /* read from file*/
    if(c != EOF){
          printf("%c",c); /*  display on screen*/
    }
  }
  fclose(fr);
  return 0;
}

I have not tested it yet but probably work. Please let me know if there is some problem with the code i will edit it.

Edit1:char c; in line 5 is initialized as ' ' for dealing with UB.

Edit2:adding condition (c != EOF) to while loop in line 7, for not giving reason to infinite loop.

Edit3:adding if statement to line 10 for not printing EOF which can be reason for odd results.

Baran
  • 131
  • 8
2

For whatever it's worth, here's an example that uses getline

#include <stdio.h>

int main()
{
  FILE *fr;
  char *line = NULL;
  size_t len = 0;
  ssize_t nread;

  if (!(fr = fopen("prog.txt", "r"))) {
    perror("Unable to open file");
    return 1;
  }
  nread = getline(&line, &len, fr);
  printf("line: %s, nread: %ld\n", line, nread);

  fclose(fr);
  return 0;
}

Some notes:

  • getline() can automatically allocate your read buffer, if you wish.
  • getline() returns the end of line delimiter. You can always strip it off, if you don't want it.
  • It's ALWAYS a good idea to check the status of I/O calls like "fopen()".
FoggyDay
  • 11,962
  • 4
  • 34
  • 48