user20842454566
user20842454566

Reputation: 115

Reading from text file skips first line

I'm using strtok to read from a file that looks like this. Thanks to the answer of my last question, the seg fault went away. However, I'm now having a problem of the the read in file, not being read on the first line

Once again: I have a file that looks like this (test.txt)

5f6
2f6

And a c file that looks like this:

#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char * argv[])
{
    char buf[100];
    char *ptr;
    char *ptr2;
    char *ptr3;
    char *ptr4;
    int a,b,c,d;
    FILE *file;

    initscr();
    cbreak();
    noecho();

    if (argc > 1)
     {
        file = fopen(argv[1], "r");
        if (file == NULL) //doesn't return null
            return -1;
        while (fgets(buf,100,file) != NULL)
         {
            ptr  = strtok(buf,"f");
            ptr2 = strtok(NULL," ");
            ptr3 = strtok(NULL,"f");
            ptr4 = strtok(NULL," ");
            if (ptr != NULL)
                a = atoi(ptr);
            if (ptr2 != NULL)
                b = atoi(ptr2);
            if (ptr3 != NULL)
                c = atoi(ptr3);
            if (ptr4 != NULL)
                d = atoi(ptr4);

            mvprintw(0,0,"Values are a %d b %d c %d d %d",a,b,c,d);
         }
     }
    refresh();
    getchar();
    endwin();

    return 0;
}

from the text file, the values should be(EXPECTED OUTPUT): a = 5, b = 6, c = 2, d = 6;

But the program outputs: a = 2, b = 6, c = 0, d = 0

I've tried to modify entries of the text file(change the values around), but that doesn't seem to yield any improvement. I've also tried to change directory, re write this code in another directory with a new file (in case it was some sort of a memory issue, but all to no avail.) Any help would be much appreciated.

Upvotes: 0

Views: 1440

Answers (1)

M Oehm
M Oehm

Reputation: 29126

Two things: fgets will read lines, i.e. until either a new-line character is found or the buffer is full. With your current file layout, you can't get all four values with one fgets.

You actually read two lines from the file, but you overwrite the results, because you don't advance the cursor position; you always write at (0, 0). So you only see the last line's values.

Upvotes: 1

Related Questions