gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:11:08 25 4
gpt4 key购买 nike

我正在编写一个代码,它从 .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
}

提前感谢您的回复。

最佳答案

好吧,这个问题的答案其实很简单,谢谢大家的帮助!以下是 future 可能的旅行者的代码:

//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

}

关于c - 在C中打开文件如何防止读取错误的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com