【发布时间】:2015-09-11 16:54:53
【问题描述】:
我对 C 有点陌生,但基本上我有一个问题,我需要从文件中读取“-1”。遗憾的是,这意味着我遇到了文件的过早结束,因为 EOF 常量在我的编译器中也是 -1。
对此会有什么样的解决方法?我可以使用另一个函数来读取它,将 EOF 更改为我可以使用的东西吗?
提前致谢。
人们要求的代码
int read() {
int returnVal; // The value which we return
// Open the file if it isn't already opened
if (file == NULL) {
file = fopen(filename, "r");
}
// Read the number from the file
fscanf(file, "%i", &returnVal);
// Return this number
return returnVal;
}
这个数字随后会与 EOF 进行比较。
好吧,这可能是不好的做法,但我将代码更改为以下
int readValue() {
int returnVal; // The value which we return
// Open the file if it isn't already opened
if (file == NULL) {
file = fopen(filename, "r");
}
// Read the number from the file
fscanf(file, "%i", &returnVal);
if (feof(file)) {
fclose(file);
return -1000;
}
// Return this number
return returnVal;
}
因为我知道我永远不会从我的文件中读取任何这样的数字(它们的范围约为 [-300, 300]。感谢你们的所有帮助!
【问题讨论】:
-
EOF 常量为 -1 并不重要...永远不会出现您检查已读取的值并由于 -1 以外的任何原因返回为 -1 的情况在那里(或者没有读取任何内容并且您的内存恰好包含-1)。发布您认为遇到问题的代码,您可以得到帮助,但如果没有这些代码,则按照 Stack Overflow 标准,这个问题是不完整的。