0

我是 C 编程新手,运行程序时得到一个 THREAD 1: EXC_BAD_ACCESS(code = 1, address 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]);
    }
}
4

3 回答 3

3

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

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

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

于 2013-10-03T00:04:12.467 回答
1

另外值得注意的是,您的文件中可能有超过 100 个数字,在这种情况下,您将超出数组的大小。尝试用以下代码替换 while 循环:

for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
    array[i] = num;
    printf("%d", array[i]);
}
于 2013-10-03T00:09:01.900 回答
0

您是否创建了本地文件“data.txt”?

touch data.txt
echo 111 222 333 444 555 > data.txt

检查您的文件打开是否成功。

这是一个工作版本,

#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
    FILE *fh; //reminder that you have a file handle, not a file name
    if( ! (fh= fopen("data.txt", "r") ) )
    {
       printf("open %s failed\n", "data.txt"); exit(1);
    }

    int array[100];
    int idx = 0; //never use 'i', too hard to find
    int num;
    while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
        array[idx] = num;
        printf("%d,", array[idx]);
        idx++;
    }
    printf("\n");
    fclose(fh);

    //you only have idx numbers (0..idx-1)
    int jdx;
    for(jdx = 0; jdx<idx; jdx++)
    {
        printf("%d,", array[jdx]);
    }
    printf("\n");
}
于 2013-10-03T02:33:55.043 回答