c - 错误的输出 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
解决方案
好吧,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
看看事情,如果你有问题,请告诉我。
推荐阅读
- git - 重新计算合并冲突(即如何生成冲突标记)
- python - 例外:“模块”对象不可迭代
- java - JADE 代理 - 异常消息:调度程序错误 - 原因:远程站点中的 DispatcherException。object-id 没有骨架
- javascript - 为什么 ES6 类方法没有出现在原型中?
- amazon-web-services - Terraform,获取数据源长度的计数
- r - 在 R Markdown YAML 中包含 css 文件的文件路径
- amazon-web-services - pod 卡在 AWS EKS 中的“ContainerCreating”状态
- javascript - Parsfloat 和货币问题
- webpack - 什么是 webpack 的“相同文件名错误”?
- asp.net - 虚拟主机时禁用端口 137 和 139