Thread: fgets skipping lines

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    11

    fgets skipping lines

    Hello all. Im having and issue when reading from a .txt file. Some of the lines in it are being skipped by the while loop and I have no idea why. Any insight is greatly appreciated.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv) {
    	char str[80];
    	FILE *fIn;
    	fIn = fopen("./input.txt", "r");
    	int i;
    
    	while (fgets(str, 1024, fIn) != NULL) {
    		fgets(str, 1024, fIn);
    		printf("%s",str);
    	}
    	fclose(fIn);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So ... be the computer. Clear your mind, and walk through the code. As you go, compare how many times you read from the file, compared to the number of times you print something out.

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    11
    ok i see whats happening, now my question becomes, "how do i detect the end of the file without calling fgets??"

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You don't. You must call fgets to detect the end of file. But why call fgets twice? Why not just call it ... once?

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    > "how do i detect the end of the file without calling fgets??"
    You look at the return result of fgets - which you're doing anyway.

    > while (fgets(str, 1024, fIn) != NULL)
    Will read each line in turn.

    HOWEVER!!!!
    > char str[80];
    If you go around LYING about buffer sizes, you're screwed anyway.

    So perhaps pick a decent buffer size (BUFSIZ is a good value to use), and write
    while (fgets(str, sizeof(str), fIn) != NULL)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets skipping, buffer issue?
    By TLW in forum C Programming
    Replies: 2
    Last Post: 02-20-2011, 08:15 PM
  2. reading a file with getline and skipping lines..
    By kocmohabt33 in forum C++ Programming
    Replies: 2
    Last Post: 01-29-2011, 12:37 AM
  3. fgets and skipping a line...
    By pollypocket4eva in forum C Programming
    Replies: 3
    Last Post: 01-03-2009, 01:42 PM
  4. skipping lines
    By LightKnight86 in forum C++ Programming
    Replies: 2
    Last Post: 09-20-2003, 08:26 PM
  5. compiler skipping lines..?
    By Linette in forum C++ Programming
    Replies: 6
    Last Post: 04-12-2002, 11:59 PM