Copying the contents of one file to another in C ++

I use the following program to try to copy the contents of the src file to another, dest, in C ++. The simplified code is given below:

#include <fstream>
using namespace std;
int main()
{
  fstream src("c:\\tplat\test\\secClassMf19.txt", fstream::binary);
  ofstream dest("c:\\tplat\\test\\mf19b.txt", fstream::trunc|fstream::binary);
  dest << src.rdbuf();
  return 0;
}

When I created and executed the program using the CODEBLOCKS ide with the GCC Compiler on Windows, a new file was created named ".... mf19.txt", but the data was not copied, but filesize = 0kb. I am sure that I have some data in "... secClassMf19.txt".

I have the same problem when I compiled the same program in Windows Visual C ++ 2008.

Can someone explain why I get this unexpected behavior, and more importantly, how to solve the problem?

+3
source share
3

, , . , , . :

int main()
{
    std::fstream src("c:\\tplat\test\\secClassMf19.txt", std::ios::binary);
    if(!src.good())
    {
        std::cerr << "error opening input file\n";
        std::exit(1);
    }
    std::ofstream dest("c:\\tplat\\test\\mf19b.txt", std::ios::trunc|std::ios::binary);
    if(!dest.good())
    {
        std::cerr << "error opening output file\n";
        std::exit(2);
    }
    dest << src.rdbuf();
    if(!src.eof())
        std::cerr << "reading from file failed\n";
    if(!dst.good())
        std::cerr << "writing to file failed\n";
    return 0;
}

, , .

, std::ios::in|std::ios::binary std::ios::binary.

+4
+1

, src fstream, . , src ifstream, . ( !)

( sbi), , , . ( ofstream) , , rdbuf() , .

, , , , , . , , . . (, 1 , , ) , . , , , .

And you will probably find that your OS is even more efficient at copying files if you use your own APIs, but then it becomes less portable. You can look at the Boost file system module for a portable solution.

+1
source

Source: https://habr.com/ru/post/1767141/


All Articles