测试.txt:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccc
The color of the car is blue
代码:
FILE *fp;
char var[30];
int result
if( (fp = fopen( "test.txt", "r")) == NULL) //open for read
printf("ERROR");
result = fscanf( fp, "The color of the car is %s", &var);
执行后:
opens file (not NULL and was able to execute an append when testing)
result = 0 //zero- in the case of a matching failure....?
errno = 0;
and var is garbage.
我期待 fscanf() 匹配“blue”。
我应该如何正确地将 blue 放入 var 中? 谢谢。
最佳答案
如何使用 fgets
代替:
char *search = "The color of the..";
char *p;
while (fgets(var, SIZE, stdin)) {
/* Does it have what we want ? */
if ((p = strstr(var, search)))
break;
}
if (p)
p += strlen(str);
关于c - 此文本文件上的 fscanf() 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167058/