代码之家  ›  专栏  ›  技术社区  ›  CodeMonkey

如何检查文件复制和写入是否成功

  •  4
  • CodeMonkey  · 技术社区  · 7 年前

    我使用C++ 11以这样的方式复制一个文件:

    std::ifstream  src(srcPath, std::ios::binary);
    std::ofstream  dst(destinationPath, std::ios::binary);
    dst << src.rdbuf();
    

    我正在通过以下方式创建新文件:

    std::ofstream out(path);
    out << fileContent;
    out.close();
    

    在这两种情况下,如何检查操作是否实际成功或失败?

    1 回复  |  直到 7 年前
        1
  •  5
  •   acraig5075    7 年前

    operator bool 是为 ostream& 返回流插入。所以你可以用 if 声明:

    if (dst << src.rdbuf())
        { // ... }
    
    if (out << fileContent)
        { // ... }