【问题标题】:How to count the number of integers in a file in C? [duplicate]如何在 C 中计算文件中的整数个数? [复制]
【发布时间】:2016-04-17 03:55:26
【问题描述】:

我有这段代码,它从第一个参数读取一个文件到 main 并计算其中存储的整数个数。

#include<stdio.h>
#include <sys/wait.h>
#include <stdlib.h>

int array[100000];
int count = 0;
int main(int argc, char* argv[]){
    FILE* file;
    int i;


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

    while(!feof(file)){
        fscanf(file, "%d", &array[count]);
        count++;
    }

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

我执行这个文件时的输出是

 a[0] = 1

 a[1] = 2

 a[2] = 3

 a[3] = 4

 a[4] = 5

 a[5] = 6

 a[6] = 7

 a[7] = 8

 a[8] = 9

 a[9] = 10

 a[10] = 0

为什么 count 1 的值比预期的大?

我使用“./a.out /home/ghost/Desktop/file.txt”的输入文件如下:

1 2 3 4 5 6 7 8 9 10

【问题讨论】:

  • 第一个错误while(!feof(file))错了!你应该阅读fscanf() 的文档,然后你会想出这个while (fscanf(file, "%d", array[count++]) == 1); 而且,绝对不需要全局变量。
  • 如果您费心检查fscanf 的返回值(您应该始终这样做),您会发现/避免这个错误。
  • @iharob 好吧,array 作为全局变量比堆栈中的局部变量安全得多,具有这种大小......并且在这样的 sn-p 中使用 malloc 只会从真正的问题上转移注意力。所以在上下文中使用全局变量是有意义的。
  • @hyde 我完全不同意。如果数组在main() 中定义,它将与整个程序具有相同的生命周期。
  • @iharob 我不是在谈论生命周期,而是在谈论堆栈大小受到限制。为程序的生命周期分配 5%(典型 8MB 中的约 400 KB)是相当有问题的。

标签: c file


【解决方案1】:
while(!feof(file)){
    fscanf(file, "%d", &array[count]);
    count++;
}

你需要检查fscanf()的返回码,而不是检查eof:

while(fscanf(file, "%d", &array[count]) == 1)
    count++;

但最好也建立一些安全性,例如:

#define NUM_ITEMS 1000

int array[NUM_ITEMS];

int main(int argc, char* argv[]){
{
    FILE* file;
    int i, count = 0;

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

    if (!file) {
        printf("Problem with opening file\n");
        return 0; // or some error code
    }

    while(count < NUM_ITEMS && fscanf(file, "%d", &array[count]) == 1)
        count++;

    fclose(file);

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

    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2011-03-05
    • 2013-05-05
    • 2011-11-29
    相关资源
    最近更新 更多