我正在编写一个 C 程序来执行以下操作: - 从文件中以 block 的形式读取(读入数组) - 对数组中的数据进行修改 - 然后将数组数据写入新创建的文件
文件处理循环代码如下:
//(buffer_array is a dynamically allocated char array and quite big)
while (0 < (bytes_read = fread(buffer_array, 1, sizeof(buffer_array), source_file))) {
modification_function(buffer_array, .....);
bytes_written = fwrite(buffer, 1, bytes_read, target_file);
//Checking for errors - is this the right way of doing error checking?
if(bytes_written != bytes_read || ferror(target_file) || ferror(source_file)) {
/* Handle file errors */
}
}
用于错误检查的 if 条件是否太过分了?
这样使用ferr就够了吗? if(bytes_writing != bytes_read) {/在这里调用ferror来找出问题所在/}?
在这种情况下使用ferror和其他错误检查机制的最佳方法是什么?
谢谢! :)
最佳答案
正如您在问题底部所述,使用ferror就足够了:
if (bytes_written != bytes_read) {
// determine what to do based on ferror()
}
这是正确且简洁的。
关于使用 fread 和 fwrite 时正确使用错误检查(包括 Ferr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266673/