Marcello Grechi Lins
Marcello Grechi Lins

Reputation: 3410

Parsing Specific Input File Using Fscanf

i`ve been trying o use fscanf to read the an input file on my application.

This is the input file

3
Process#1 - 2Kb
3
exec 20

io 5

exec 50

Process#2 - 8Kb

1

exec 100

Process#3 - 8Kb

4

exec 50

io 50

exec 50

io 50

First of all i want to read the First "3", which i am having no problems doing so.

After that, i will need to read the information after the # (which is 1) and the number right after the "kb" string (which is 2).

Why is this fscanf failing to do so ?

fscanf(inputFile, "Process#%d - %dKb", &id, &mem ); 

How can i do it ?

Thanks in advance

Upvotes: 1

Views: 347

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753465

Probably because the newline left behind after the 3 is not being recognized by the P in Process.

This is why many people avoid scanf(); it is usually simpler to use fgets() or a related function (but not gets()!) and then use sscanf().


Demo code

Notice the rigorous checking of the return from scanf(). If you don't do that, you will not know when things have gone wrong. Note that the check is for the correct number of conversions, too.

#include <stdio.h>
int main(void)
{
    int i;
    int id;
    int mem;

    if (scanf("%d", &i) != 1)
        printf("oops!\n");
    /* With    space - reads past newline on first line */
    /* Without space - prints 'thank goodness!' */
    if (scanf(" Process#%d - %d", &id, &mem) != 2)
        printf("thank goodness!\n");
    return 0;
}

Upvotes: 3

Related Questions