在C.中打开文件如何防止读取错误的数据类型

时间:2016-03-04 16:04:23

标签: c file

我正在编写一个代码,它从.txt文件中读取十进制数字并将它们转换为U2表示法。如果文件中有一些随机文本,我需要保护代码,我不知道该怎么做如果我的.txt中有文本而不是十进制数字,那么我需要显示一些错误并停止程序。 这是打开文件的函数:

//Opening file
int openFile(long arr[]) {

    FILE *f = fopen("numbers.txt", "r");

    //if something went wrong with opening our file
    if(f == NULL) {
        perror("File could not be opened.");
        return;
    }
    int i = 0;  //for navigation around our array into which we
                //save numbers from opened file
    while(!feof(f)) {
        fscanf(f, "%d", &arr[i]); //loading numbers from file
        toU2(arr[i]);             //calling out function which converts numbers to U2
        i++;
    }
    fclose(f);                      //closing file
}

提前感谢您的回复。

1 个答案:

答案 0 :(得分:1)

好的,这个问题的答案实际上非常简单,谢谢你的帮助! 以下是可能的未来旅行者的代码:

//Opening file
int openFile(long arr[]) {

FILE *f = fopen("numbers.txt", "r");

//if something went wrong with opening our file
if(f == NULL) {
    perror("File could not be opened.");
    return;
}
int i = 0;  //for navigation around our array into which we
            //save numbers from opened file
int x = 0;
while(!feof(f)) {
    if(fscanf(f, "%d", &arr[i])){ //loading numbers from file
        toU2(arr[i]);             //calling out function which converts numbers to U2
    } else {                      //if loaded data was not an integer
        printf("Error");
        break;
    }
    i++;
}
fclose(f);                      //closing file

}