概述
在使用fgets()
时,我有一些错误检查代码,在fgets()
返回null
但未到文件结尾时执行一些纠正操作。我想测试这段代码,以验证它是否按预期工作。
是否有一种标准方法来触发fgets()
失败?无论是通过手动手段(在调用fgets()
之间某种方式删除文件),还是通过一些测试设置(提供一个已知的“损坏”文件),或者其他一些方式?
最小可重现示例
fgets_fail_test.cpp:
// Test code to show minimally reproducible example of fgets() error handling
// The desire is to manually trigger a failure in fgets()
#include <errno.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp = fopen("test_file.txt", "r"); //assume this works, not testing this
char buf[100]; //assume large enough to hold data
unsigned int lineno = 1;
while (fgets(buf, 100, fp)) {
std::cout << buf;
lineno++;
}
if (feof(fp)) {
std::cout << "End of file encountered.\n";
}
else if (ferror(fp)) { // how do I trigger an fgets error to cause this to return true?
printf("Encountered read error at line no %u. Error: %d, %s.\n",
lineno,
errno,
strerror(errno));
}
fclose(fp); // assume this works, not testing this
return 0;
}
test_file.txt:
ABCDEFG
HIJKLMN
OPQRSTU
VWXYZ
The quick brown fox
jumped over the
lazy dog.
Goodbye.
理论
虽然我可以用一些测试脚手架来替换问题中的代码(编写一个保持内部状态的fgets包装器,增加计数器,当它达到第N行时返回null
并手动设置文件错误和errno),但我觉得应该有一种“内置”的方法来实现这一点?
如果唯一的解决方案是搭建脚手架,那我就这样做。说实话,也许我在这里想得太聪明了。
(int)charater < 32
。 - Ripi2