Thread: Skip the first line when reading from a file?

  1. #1
    Registered User
    Join Date
    Feb 2012

    Skip the first line when reading from a file?


    I'm trying to read a file with sscanf. The format looks like this:

    text text number
    text text number

    and I have this:
    while (fgets(line, BUFSIZE, infilep) != NULL) {
                    minfo *minfop = malloc(sizeof(minfo));
                    sscanf(line, "%[^ ] %[^ ] %s", 
                    minfop->v1, minfop->v2, minfop->e);

    I'm saving the structs to a list later on but that is kind of irrelevant for now. This code works fine, but the thing is I wan't to read only the first line, because that line only has one number. Then I wan't to continue with sscanf, but from the second line.

    How do I do this?

    Help appreciated!

  2. #2
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Why not read just the first line OUTSIDE the loop using fgets and do what you want with it. Then, when you enter the loop, the next fgets will read the 2nd, 3rd, 4th, etc. lines.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    You could test the return value of scanf, and if it isn't 3, use continue before you add that (invalid) struct to the list.

    BTW, %[^ ] in that context would be exactly the same as %s, since %s stops on (and does not include) whitespace.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Feb 2012
    Works great, thanks for the help guys!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 12-13-2010, 02:13 PM
  2. reading words line by line from a file
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 12:34 AM
  3. Reading Input from a file, line-by-line
    By Acolyte in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 01:03 PM
  4. Skip line in file - fscanf
    By Noori88 in forum C Programming
    Replies: 2
    Last Post: 05-27-2007, 06:57 AM
  5. reading a file line by line and char *
    By odysseus.lost in forum C Programming
    Replies: 8
    Last Post: 05-31-2005, 09:47 AM