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

Yon*_*Nir 5 c++ ifstream ofstream c++11

我正在使用C++ 11以这种方式复制文件:

std::ifstream  src(srcPath, std::ios::binary);
std::ofstream  dst(destinationPath, std::ios::binary);
dst << src.rdbuf();
Run Code Online (Sandbox Code Playgroud)

我这样创建一个新文件:

std::ofstream out(path);
out << fileContent;
out.close();
Run Code Online (Sandbox Code Playgroud)

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

acr*_*075 5

operator boolostream&流插入的返回定义.因此,您可以通过if声明测试成功:

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

if (out << fileContent)
    { // ... }
Run Code Online (Sandbox Code Playgroud)