PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to take first row from this list of text?

 October 30, 2022     c, eof, file-read, function     No comments   

Issue

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.



Answered By - anastaciu
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing