【问题标题】:I'm trying to write a C program to store integers from a file into an array, but it doesn't work. Can someone help me?我正在尝试编写一个 C 程序来将文件中的整数存储到数组中,但它不起作用。有人能帮我吗?
【发布时间】:2019-09-06 13:40:13
【问题描述】:

似乎我不太了解文件流的工作原理。我的文本文件现在包含以下整数:1 10 5 4 2 3 -6,但我希望程序能够从文件中读取任意数量的整数,如果它改变的话。

显然我什至没有使用正确的功能。 我写的代码如下:

 int main() {
     printf("This program stores numbers from numeri.txt into an array.\n\n");
     int a[100];
     int num;
     int count = 0;

     FILE* numeri = fopen("numeri.txt", "r");

     while (!feof(numeri)) {
         num = getw(numeri);
         a[count] = num;
         if (fgetc(numeri) != ' ')
             count++;
     }

     int i;
     for (i = 0; i < count; i++) { printf("%d ", a[i]); }

     return 0;
}

我希望它打印出包含存储数字的数组,但我得到的只是:540287029 757084960 -1

谁能帮我理解我做错了什么,也许可以告诉我如何正确编写这种代码?

【问题讨论】:

  • 什么是getw?它有什么作用?
  • man putw/getw : getw() 从流中读取一个单词(即一个 int)。提供它是为了与 SVr4 兼容。我们建议您改用 fread(3)。 putw() 将单词 w(即一个 int)写入流。提供它是为了与 SVr4 兼容,但我们建议您改用 fwrite(3)。
  • @chux 啊,这解释了问题。 OP 正在读取 text 文件,getw 就像从 binary 文件中读取一样。所以简单的解决方案可能是使用fscanf(并记得检查what it returns,作为循环条件的一部分)。
  • 我发现潜在的缓冲区溢出是由于count 可能会超过 100,这是您的数组 a 的大小。这会导致未定义的行为。

标签: c arrays file


【解决方案1】:

我已根据 cmets 修复了您的代码。我使用fscanf 从文件中读取数据,并通过检查count &lt; 100 并检查fscanf 是否恰好填充了一个参数来限制可以存储在数组中的数字数量。

另外,我检查了文件是否可以打开,只是为了安全。如果打不开,就打印错误信息和return 1。

int main() {

    printf("This program stores numbers from numeri.txt into an array.\n\n");
    int a[100] = {0};
    int num;
    int count = 0;
    int i = 0;

    FILE* numeri = fopen("numeri.txt", "r");
    if (numeri == NULL) {
        printf("Can't open file\n");
        return 1;
    }

    while (count < 100 && fscanf(numeri, "%d", &num) == 1) {
       a[count++] = num;
    }

    for (i = 0; i < count; i++) { printf("%d ", a[i]); }

    return 0;
}

【讨论】:

  • fscanf(numeri, "%d", &amp;num) != EOF --> fscanf(numeri, "%d", &amp;num) == 1 可以很好地处理非数字文本
  • 非常感谢!你真的帮了我大忙。
  • @reaper_ What should I do when someone answers my question?。简而言之:赞成、接受、不要添加感谢信。
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多