如何使用C捕获FILE IO中的错误?

问题描述 投票:0回答:2

我正在使用以下 C 代码片段来复制文件:

#define CHUNK 4096 
char buf[CHUNK];
FILE *file , *out;
size_t nread;

file = fopen("test", "rb");
out = fopen("out", "wb");

if (file) {
    while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
        fwrite(buf, 1, nread, out);
    if (ferror(file)) {
        /* Not getting error here */
    }
    fclose(file);
    fclose(out);
}

我的文件非常大(200 MB),如果在读取、写入过程中移动或删除文件,我必须处理错误。我怎样才能做到这一点?

让我再澄清一点,无论我如何通过某种 wifi 方式访问路径。因此,如果 wifi 将断开连接,那么我将如何收到错误..

c io large-files
2个回答
2
投票

如果写入的字节数与

nread
参数不同,这将指示错误,因此:

if (fwrite(buf, 1, nread, out) != nread) {
  // error handling
}

在 Windows 下,您可以使用

_lock_file();
锁定文件以防止其他进程删除该文件:

#include <stdio.h>

if (file) {
   // lock file
   _lock_file(file);

   while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
      fwrite(buf, 1, nread, out);

      // unlock and close the file
      _unlock_file(file);
      fclose(file);
      fclose(out);
}

0
投票

您可能应该以写入模式打开输出文件,即

"wb"

如何处理错误:检查I/O函数的返回值,并尝试处理错误。您可以使用

feof()
ferror()
来分析哪里出了问题。确保在调用它们中的任何一个之前始终执行一些 I/O(不要在读取之前尝试确定 EOF)。

© www.soinside.com 2019 - 2024. All rights reserved.