【问题标题】:Trying to read a series of integers from a file试图从文件中读取一系列整数
【发布时间】:2015-02-05 03:12:52
【问题描述】:

我正在编写一个练习程序来从文件中读取整数并对其进行排序。我对 C 中的文件 IO 有点困惑。到目前为止我所拥有的如下,我希望有人可以看看它并提供任何更正/建议,如果他们有任何...

            // TODO: Open input file and do same as above
            char *mode = "r";
            FILE *fp = fopen(inputFile, mode);

            if(fp == NULL){
                    fprintf(stderr, "Can't open input file!");
                    exit(1);
            }

            // Load the numbers into a buffer and get a count
            int buffer[100];
            int count = 0;
            while(fscanf(fp, "%d", &buffer[count]) == 1) {
                    count++;
            }


            // Initialize the array with the proper size
            integers = (int*)malloc(sizeof(count*sizeof(int)));


            // Load the integers into the array
            rewind(fp);
            for(int i = 0; i < count; i++){
                    if(fscanf(fp, "%d", &integers[count] != 1)){
                            fprintf(stderr, "Error loading integers into array");
                            exit(1);
                    }

            }

【问题讨论】:

  • 你在哪里清除整数数组?
  • @PeerNet 它是一个全局 int 指针。我只包含了我的程序的一个功能
  • @JayB 你知道nfscanf() 中做了什么吧?读取的字符数,如果文件中有 10 个字符,你的输入是什么?
  • @Gopi 仅供参考,请参阅this answer。这就是代码的来源,但 OP 误用了答案。
  • @user3386109 我完全按照你写的那样做,但我正在尝试重新应用它来读取文件......

标签: c arrays io


【解决方案1】:

fscanf() 返回成功读取的元素数,因此请检查要读取的所需元素数,在您的情况下,您可以将值读取到数组并增加索引。以后使用index的值来分配内存。

int *temp;
integers = malloc(sizeof(int)));
while(fscanf(fp, "%d", &integers[index]) == 1)
{
    index++;
    temp = realloc(integers,sizeof(int) * (index+1));
    if(temp != NULL)
    integers = temp; 
}

【讨论】:

  • 如果你关心性能,你应该一次 realloc() 比单个 int 更大的块。
  • @JohnZwinck 我认为,性能并不是这个项目真正关心的问题。谢谢
猜你喜欢
  • 2013-05-18
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 2021-12-26
相关资源
最近更新 更多