Thread: How do i read the end of the line in a txt or dat file?

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    33

    How do i read the end of the line in a txt or dat file?

    How do i read the end of the line in a txt or dat file? I treid using fscanf in a while loop like this
    Code:
    while(fscanf(pfile,"%c") != EOF && fscanf(pfile,"%c") != '\n')
    {
     char c = ' ';
     fscanf(pfile,"%c",&c);
     str += c;
    }
    The reason why its important to stop after each line is that i need the program to read the data from each line separately. It would be great if someone could tell me would i am doing wrong,How i can fix it and What i should use to do this. I have searched everywhere on the c++ ref site and the internet on how to do this but i just cant find anything and if i can it just does int make any sense.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    That code should give compiler warnings, if not, turn up the warning level.

    Read the documentation for the functions you use. fscanf does not return the char it read, though fgetc does. Also, you must provide a place for fscanf to actually store the char it reads (like the fscanf on line 4). Once you fix that, you don't want to call a read function twice in that loop, otherwise you read two characters each time. The first char, you check for EOF, the second for '\n'. This is problematic if the EOF is at an even position, or the newline at an odd position, in the line. Read the char once per loop, but check the variable where you store it in both halves of the loop condition:
    Code:
    int ch;  // yes, an int...fgetc must be able to return all char values plus other values like EOF
    while ((ch = fgetc(pfile)) != EOF && ch != '\n')

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I guess the question is: one, is fscanf necessary and two, if you do use fscanf, do you have to use %c? It really really really looks like you just want to use fgets.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 21
    Last Post: 08-07-2011, 09:55 PM
  2. Read file line by line and interpret them
    By sombrancelha in forum C Programming
    Replies: 8
    Last Post: 03-17-2011, 09:48 AM
  3. Read text file line by line and write lines to other files
    By magische_vogel in forum C Programming
    Replies: 10
    Last Post: 01-23-2011, 10:51 AM
  4. Read line by line from file with EOL different that OS EOL
    By hanniball in forum C++ Programming
    Replies: 2
    Last Post: 09-17-2010, 09:06 AM
  5. How do I read file line by line?
    By Blurr in forum C Programming
    Replies: 1
    Last Post: 09-22-2001, 12:32 AM