C++ 复制文件 文件路径变量是char
时间: 2023-11-14 11:43:38 浏览: 31
如果文件路径变量是 `char` 类型,你可以使用 C 语言中的标准库函数 `fopen`、`fread` 和 `fwrite` 来复制文件。以下是一个示例代码:
```cpp
#include <iostream>
#include <cstdio>
bool copyFile(const char* sourcePath, const char* destinationPath) {
FILE* sourceFile = fopen(sourcePath, "rb");
if (!sourceFile) {
std::cout << "Failed to open source file." << std::endl;
return false;
}
FILE* destinationFile = fopen(destinationPath, "wb");
if (!destinationFile) {
std::cout << "Failed to create destination file." << std::endl;
fclose(sourceFile);
return false;
}
const size_t bufferSize = 4096;
char buffer[bufferSize];
size_t bytesRead;
while ((bytesRead = fread(buffer, sizeof(char), bufferSize, sourceFile)) > 0) {
fwrite(buffer, sizeof(char), bytesRead, destinationFile);
}
if (ferror(sourceFile)) {
std::cout << "Error occurred while reading source file." << std::endl;
fclose(sourceFile);
fclose(destinationFile);
return false;
}
if (ferror(destinationFile)) {
std::cout << "Error occurred while writing to destination file." << std::endl;
fclose(sourceFile);
fclose(destinationFile);
return false;
}
fclose(sourceFile);
fclose(destinationFile);
return true;
}
int main() {
const char* sourcePath = "path/to/source/file.txt";
const char* destinationPath = "path/to/destination/file.txt";
if (copyFile(sourcePath, destinationPath)) {
std::cout << "File copied successfully." << std::endl;
} else {
std::cout << "Failed to copy file." << std::endl;
}
return 0;
}
```
将代码中的 `sourcePath` 和 `destinationPath` 替换为实际的文件路径。代码使用了 `fopen` 函数以二进制模式打开源文件和目标文件,并使用 `fread` 和 `fwrite` 函数来读取源文件内容并写入目标文件。最后,关闭源文件和目标文件,并根据复制的成功与否输出相应的信息。