使用标准流将文件复制到其他位置

Dev*_*vvy -1 c++

我正在尝试创建一个方法,将文件复制到我的项目本地的文件夹.我很困惑,因为根据我的理解,这应该有效.我决定创建一个简单的文本文件来测试我的复制文件方法,但它似乎没有工作.

std::string newFile="Files\\newText.txt";

std::ifstream oldFile("C:\\Users\\dtruman\\Documents\\oldText.txt", std::ios::binary | std::ios::in);
std::ofstream newTarget(newFile, std::ios::binary | std::ios::out);

char c;
while(oldFile.get(c));
{
    std::cout << c << std::endl;
    newTarget.put(c);
}

newTarget.close();
oldFile.close();
Run Code Online (Sandbox Code Playgroud)

其中一些东西是我摆弄代码.我的问题是,无论我似乎做什么,似乎永远不会正确复制文件,新文本文件的内容总是与原始文件不同.我错过了一些东西,据我所知,这段代码应该可行.

R S*_*ahu 5

这条线

while(oldFile.get(c));
Run Code Online (Sandbox Code Playgroud)

消耗整个文件,没有任何副作用,因为;最后.

你需要:

while(oldFile.get(c)) // Without the ;
{
    std::cout << c << std::endl;
    newTarget.put(c);
}
Run Code Online (Sandbox Code Playgroud)