在不同的编程语言中,复制文件内容的方法有所不同。以下是几种常见编程语言的示例代码:
C语言示例
```c
include include int fileCopy(const char *destFileName, const char *srcFileName) { FILE *destFile = fopen(destFileName, "ab"); if (destFile == NULL) { return 0; } FILE *srcFile = fopen(srcFileName, "rb"); if (srcFile == NULL) { fclose(destFile); return 0; } size_t len; char buffer; while ((len = fread(buffer, 1, sizeof(buffer), srcFile)) > 0) { fwrite(buffer, 1, len, destFile); } fclose(srcFile); fclose(destFile); return 1; } int main() { const char *destFileName = "destination.txt"; const char *srcFileName = "source.txt"; if (fileCopy(destFileName, srcFileName)) { printf("文件复制成功\n"); } else { printf("文件复制失败\n"); } return 0; } ``` Python示例 ```python import shutil def copy_file(src_path, dest_path): shutil.copy2(src_path, dest_path) 使用示例 copy_file("source.txt", "destination.txt") ``` Java示例 ```java import java.io.*; public class FileCopy { public static void main(String[] args) { File source = new File("source.txt"); File destination = new File("destination.txt"); try { copyFile(source, destination); } catch (IOException e) { e.printStackTrace(); } } public static void copyFile(File source, File destination) throws IOException { if (source.isDirectory()) { for (File file : source.listFiles()) { copyFile(file, new File(destination, file.getName())); } } else { try (InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination)) { byte[] buffer = new byte; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } } } } ``` C++示例 ```cpp include include include namespace fs = std::filesystem; bool copyFile(const fs::path& source, const fs::path& destination) { try { if (fs::exists(source)) { if (fs::is_directory(source)) { fs::create_directory(destination); for (const auto& entry : fs::directory_iterator(source)) { copyFile(entry.path(), destination / entry.path().filename()); } } else { fs::copy_file(source, destination, fs::copy_options::overwrite_existing); } return true; } } catch (const fs::filesystem_error& e) { std::cerr << "Error: " << e.what() << std::endl; } return false; } int main() { fs::path source = "source.txt"; fs::path destination = "destination.txt"; if (copyFile(source, destination)) { std::cout << "File copied successfully" << std::endl; } else { std::cout << "File copy failed" << std::endl; } return 0; } ``` 这些示例展示了如何在不同编程语言中实现文件内容的复制。根据你的具体需求和使用的编程语言,可以选择合适的代码片段进行参考。