c - 此文本文件上的 fscanf() 错误?

标签 c file text stream stdin

测试.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/

相关文章:

c - 检测C中的行尾

file - 如何在没有卷的 docker 容器上验证文件下载?

Java http-读取大文件

javascript - 用结果替换加载提示的按钮

c - PNDIS_GENERIC_OBJECT 错误 C2061

c - 如何检测堆栈粉碎错误的违规代码

c - 矩阵乘法分割错误?

python - 在python中读取unicode文件

Delphi:如何以请求的宽度和行数绘制一些文本,并以省略号结尾?

python - 通过垂直拆分文本文件创建列表