读取txt文件中的数字列表并存储到数组C.

时间:2016-04-28 21:24:36

标签: c arrays file

我在阅读数字时遇到问题。我运行程序后一切都很好,但阵列中没有数字。我尝试过不同的方法在文件中写入数字而没有结果。

FILE *myFile;
myFile = fopen("numbers.txt", "r");
if (myFile==NULL)
{
    printf("Error Reading File\n");
}
else
{
tek=0;
for (i=0;i++)
{
//  tek=fgetc(myFile);
    fscanf(myFile,"%d",&tek);
    if (tek!=EOF)
    {
        redica[i]=tek;
    }
    else
    {
        break;
    }
}
getch();

1 个答案:

答案 0 :(得分:2)

请考虑对您的代码进行以下修改:

#include <stdio.h>

int main(void) {
    int tek;
    int radica[50];

    // open file
    FILE *myFile = fopen("numbers.txt", "r");
    // if opening file fails, print error message and exit 1
    if (myFile == NULL) {
        perror("Error: Failed to open file.");
        return 1;
    }

    // read values from file until EOF is returned by fscanf
    for (int i = 0; i < 50; ++i) {
        // assign the read value to variable (tek), and enter it in array (radica)
        if (fscanf(myFile, "%d", &tek) == 1) {
            radica[i] = tek;
        } else {
            // if EOF is returned by fscanf, or in case of error, break loop
            break; 
        }
    }

    // close file
    fclose(myFile);
    return 0;
}

fscanf读取的任何数字都将分配给tek,并输入数组radica,直到fscanf返回EOF,此时循环中断。如前所述,要确定何时到达文件末尾,不是与tek进行比较的变量EOF,而是fscanf的返回。