c - 尝试从 C 中的 txt 文件中读取数字时出错

标签 c file-io

我是 C 编程的新手,我得到一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 0x68) 当我运行我的程序时。我的代码的目的是从包含正数和负数的 txt 文件中读取数据并对其进行处理。

#include <stdio.h>

int main (int argc, const char * argv[]) {

    FILE *file = fopen("data.txt", "r");
    int array[100];

    int i = 0;
    int num;

    while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
        array[i] = num;
        printf("%d", array[i]);
        i++;
    }
    fclose(file);

    for(int j = 0; j < sizeof(array); j++){
        printf("%d", array[j]);
    }
}

最佳答案

之后

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

if(file == 0) {
    perror("fopen");
    exit(1);
}

只是猜测,其余代码看起来没问题,所以很可能就是这个问题。

关于c - 尝试从 C 中的 txt 文件中读取数字时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148740/

相关文章:

c - 按字符串对结构体数组进行排序

Java - 文件读/写

linux - 进程终止时丢弃打开的文件

C 编程 : How to read the whole file contents into a buffer

c - 用于在 C 中返回值的空闲内存

C 程序 - 需要左值作为赋值的左操作数 -

c - C 中预处理器条件中的字符串比较

c - C99中 "arithmetic operation"的定义是什么?

Python从文件中提取数据

c++ - 计算输入文件中有多少个 "things"被放入数组