繁体   English   中英

fscanf不扫描任何数字

[英]fscanf not scanning any numbers

我目前正在开发一个简单的C应用程序。 它将单个文件作为命令行参数,其格式如下:

1,2,3
4,5,6
7,8,9
etc.

然而,无论出于何种原因, fscanf从不扫描数字! 这是一个例子:

#include <stdio.h>

int main(int argc, char **argv) {
    FILE *file = fopen(*argv, "r");
    int i1, i2, i3;
    while (fscanf(file, "%d,%d,%d", &i1, &i2, &i3) == 3) {
        printf("Doing stuff with %d, %d, and %d...\n", i1, i2, i3);
    }
    fclose(file);
    return 0;
}

如果你以文件名作为参数运行它,那么它会立即退出,因为fscanf返回0.我尝试了几种变体,但无济于事。 如何让fscanf正确读取数字?

正如BLUEPIXY所说,你应该使用argv数组的第二个元素: argv[1]

FILE *file = fopen(argv[1], "r");

第一个元素( argv[0]*argv )是正在执行的程序的名称 - 它不是要打开的正确文件。

表面答案:错误的文件被打开,因为代码应该使用argv[1]而不是*argv

让我们更深入一点。

代码在至少2个地方遇到麻烦并且缺少错误检查。

  1. FILE *file = fopen(*argv, "r"); 后面没有一个测试file 这个经典检查不会检测到OP的问题,因为文件可执行文件是可以打开的。

  2. 来自fscanf(file, "%d,%d,%d", &i1, &i2, &i3)的返回值仅进行了轻微测试。 EOF 0 1 2 3返回值是可能的,但预计只有EOF 3 如果针对非EOF 3测试了代码,则很快就会发现问题。

需要学习的经验:保证代码,尤其是错误代码,有足够的错误检查。 从长远来看,节省了编码时间。

#include <stdio.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Unexpected argument count %d.\n", argc);
    return 1;
  } 
  FILE *file = fopen(argv[1], "r");
  if (file == NULL) {
    fprintf(stderr, "Unable to open file: \"%s\"", argv[1]);
    return 1;
  } 
  int i1, i2, i3;
  int n;
  while ((n = fscanf(file, "%d,%d,%d", &i1, &i2, &i3)) == 3) {
    printf("Doing stuff with %d, %d, and %d...\n", i1, i2, i3);
  }
  if (n != EOF) {
    fprintf(stderr, "Unexpected scan failure count %d\n", n);
    return 1;
  }
  fclose(file);
  return 0;
}

暂无
暂无

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

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