简体   繁体   English

为什么 fscanf 不能用于在 c 中首先读取文件?

[英]Why fscanf can't be used to read first on file in c?

I'm new to C programming.我是 C 编程的新手。 So I have maybe a simple question.所以我可能有一个简单的问题。 So why fscanf with fopen(read mode) can't be used?那么为什么不能使用带有 fopen(read mode) 的fscanf呢? I mean, from what I learned I must use fopen(write mode) first so then fopen(read mode) will work.我的意思是,据我所知,我必须先使用 fopen(write mode),然后 fopen(read mode) 才能工作。 If i use fopen(read mode) first before fopen(write mode) it wouldn't work like in this code.如果我在 fopen(write mode) 之前先使用 fopen(read mode),它就不会像这段代码那样工作。 Another thing is, why fscanf can't read space in this code?另一件事是,为什么fscanf无法读取这段代码中的空间? I already tried %*s while fopen(read mode) first and it didn't work.我已经先尝试了%*s while fopen(read mode) ,但它没有用。

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:测试.txt文件:

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.用给出的代码回答对我更好地学习很有帮助,谢谢。

%s reads a single word, use %[^\n] to read everything until a newline. %s读取一个单词,使用%[^\n]读取所有内容,直到换行。

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.或者使用fgets()一次读取一行,然后您可以使用sscanf()从中提取。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM