windows 如何在 Visual C++ 中复制文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2763987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:24:19  来源:igfitidea点击:

How to copy files in Visual C++?

c++windowsvisual-c++

提问by karikari

I am using Visual C++. How to copy the content of this file to another file?

我正在使用 Visual C++。如何将此文件的内容复制到另一个文件?

UINT32 writeToLog(wstring log)
 {
    wfstream file1 (LOG_FILE_NAME, ios_base::out);  
    file1 << log;       
    file1.close();

     // want to copy file1 to file2

     return 0;
 }

回答by JoeG

What exactly do you want to do? If you need a copy of the data, you can read it in and write it back out again. If you really need a copy of the file, you have to use OS specific calls.

你到底想做什么?如果您需要数据的副本,您可以读入并再次写回。如果您确实需要该文件的副本,则必须使用特定于操作系统的调用。

In many cases, reading in the file data and then writing it out again to a different file is a close enough approximation to a copy - like this:

在许多情况下,读入文件数据,然后再次将其写出到不同的文件,这与副本非常接近 - 像这样:

ifstream file1(...);
ofstream file2(...);
std::copy(istream_iterator<char>(file1),istream_iterator<char>(),ostream_iterator<char>(file2));

However that really isn't a copy - it's creating a new file with the same contents. It won't correctly handle hard links or symlinks, it won't correctly handle metadata and it will only 'copy' the default file stream.

然而,这真的不是一个副本——它正在创建一个具有相同内容的新文件。它不会正确处理硬链接或符号链接,它不会正确处理元数据,它只会“复制”默认文件流

If you need a file copy on Windows you should call one of CopyFile, CopyFileExor CopyFileTransacteddepending on your exact requirements.

如果您需要在 Windows 上进行文件副本,您应该根据您的确切要求调用CopyFileCopyFileExCopyFileTransacted 之一

回答by JoeG

Standard C++ has no file copying facility, other than reading the file into memory and writing it out again to a different file. As you are using Windows, you can use the CopyFilefunction - other OSs have similar, OS-specific functions.

标准 C++ 没有文件复制功能,除了将文件读入内存并再次将其写出到不同的文件之外。当您使用 Windows 时,您可以使用CopyFile功能 - 其他操作系统具有类似的特定于操作系统的功能。

回答by Alec Jacobson

The above code from Joe Gauterin did not work for me. I was trying to copy a .tga image file, so maybe something about istream_iterator<char>screwed it up. Instead I used:

Joe Gauterin 的上述代码对我不起作用。我试图复制一个 .tga 图像文件,所以可能是istream_iterator<char>搞砸了。相反,我使用了:

ifstream file1(...);
ofstream file2(...);
char ch;
while(file1 && file1.get(ch))
{
  file2.put(ch);
}