首页 > 解决方案 > 错误的输出 fscanf()

问题描述

您好,我正在尝试使用我编写的代码读取文件

#include <stdio.h>

int main(){
    int task_id=0;
    FILE *fp;
    fp = fopen("output","r");
    if (fp == NULL)
    {   
        printf("failed opening file");
        return 1;
    }
    else{
    fscanf(fp,"conhost.exe                   %d",&task_id);
    fclose(fp);
    printf("taskID is: %d",task_id);
    return 0;
    }
}

文件内容供参考

conhost.exe                   4272 Console                    2     13,504 K

我一直得到输出为0

标签: c

解决方案


好吧,Cara 先生(我赞扬他使用了分配抑制运算符)给了你一个很好的答案,但我还要添加一个建议。每当您阅读输入行时——使用像这样的面向行的输入函数fgets将帮助您避免一系列函数的一大堆陷阱scanf。然后,您可以使用sscanf从保存数据行的缓冲区中解析想要的信息。这确保了输入流中剩余的内容不依赖于使用的格式说明符

另外,不要对文件名进行硬编码——这就是程序参数的用途。一个简短的例子是:

#include <stdio.h>

#define MAXC 1024u  /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {  /* don't hardcode name, use arguments */

    int task_id = 0;
    char buf[MAXC];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    if (!fgets (buf, MAXC, fp)) {   /* read with line-oriented function */
        fputs ("error: EOF encountered on file read.\n", stderr);
        return 1;
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    /* parse information with sscanf (read/discard initial string) */
    if (sscanf (buf, "%*s %d", &task_id) != 1) {
        fputs ("error: invalid file format.\n", stderr);
        return 1;
    }
    printf("taskID is: %d\n",task_id);  /* output task_id */
}

示例使用/输出

$ ./bin/rd_task_id <output
taskID is: 4272

看看事情,如果你有问题,请告诉我。


推荐阅读