Home > Net >  Why fscanf can't be used to read first on file in c?
Why fscanf can't be used to read first on file in c?

Time:06-16

I'm new to C programming. So I have maybe a simple question. So why fscanf with fopen(read mode) can't be used? I mean, from what I learned I must use fopen(write mode) first so then fopen(read mode) will work. If i use fopen(read mode) first before fopen(write mode) it wouldn't work like in this code. Another thing is, why fscanf can't read space in this code? I already tried %*s while fopen(read mode) first and it didn't work.

Here is my simple code:

int main() {
    FILE *fp;
    fp = fopen("Test.txt", "r ");
    char name[100], hobby[100];
    int age;
    fscanf(fp, "Name:%*s\nAge:%d\nHobby:%*s", &name, &age, &hobby);
    printf("\nScan Result\n%s\n%d\n%s", name, age, hobby);
    fclose(fp);
    return 0;
}

Test.txt file:

Name:This is a test
Age:21
Hobby:Play games

When I run it:


Scan Result
`░
0
 >m
Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

So did I miss something? or it isn't possible? Answer with the code given would be very helpful for me to learn better, thank you.

CodePudding user response:

%s reads a single word, use %[^\n] to read everything until a newline.

Don't put & before array names when scanning into a string. Arrays automatically decay to a pointer when passed as a function argument.

    fscanf(fp,"Name: %[^\n] Age: %d Hobby: %[^\n]",name,&age,hobby);

Or use fgets() to read one line at a time, then you can use sscanf() to extract from it.

char line[100];
fgets(line, sizeof line, fp);
sscanf(line, "Name: %[^\n]", name);
fgets(line, sizeof line, fp);
sscanf(line, "Age: %d", &age);
fgets(line, sizeof line), fp;
sscanf(line, "Hobby: %[^\n]", hobby);
  • Related