使用fread和fwrite时正确使用错误检查(包括ferror)

时间:2015-05-15 18:45:17

标签: c

我正在编写一个执行此操作的C程序: - 从块中读取文件(到数组中) - 对阵列中的数据执行修改 - 然后将数组数据写入新创建的文件

文件处理循环代码如下:

//(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条件是否过度?

这样使用ferror就足够了吗? if(bytes_written!= bytes_read){/ 在这里调用ferror以找出出错的地方 /}?

在这种情况下使用ferror和其他错误检查机制的最佳方法是什么?

谢谢! :)

1 个答案:

答案 0 :(得分:0)

当您在问题的底部陈述时,使用ferror就足够了:

if (bytes_written != bytes_read) {
    // determine what to do based on ferror()
}

这是正确而简洁的。

相关问题