简体   繁体   English

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

[英]Error when trying to read in numbers from txt file in C

I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68) when I run my program.我是 C 编程的新手,当我运行我的程序时,我得到了一个 THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)。 The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.我的代码的目的是从包含正数和负数的 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]);
    }
}

After

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

Say

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

Just a guess, the rest of the code looks ok, so likely this is the problem.只是猜测,其余的代码看起来没问题,很可能这就是问题所在。

Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array.还值得注意的是,您的文件中可能有超过 100 个数字,在这种情况下,您将超出数组的大小。 Try replacing the while loop with this code:尝试用以下代码替换 while 循环:

for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
    array[i] = num;
    printf("%d", array[i]);
}

Do you have the file "data.txt" created and local?您是否创建了文件“data.txt”并且是本地的?

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

Check that your file open succeeded.检查您的文件打开是否成功。

Here is a working version,这是一个工作版本,

#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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM