当前位置:首页 C++ > 正文

c/c++ linux复制文件到指定目录

作者:野牛程序员:2023-06-27 09:27:46 C++阅读 3027

在Linux上,你可以使用C或C++编程语言来复制文件到指定目录。下面是一个示例C代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    const char* source_file = "/path/to/source/file";
    const char* destination_file = "/path/to/destination/file";

    int source_fd = open(source_file, O_RDONLY);
    if (source_fd == -1) {
        perror("Failed to open source file");
        return 1;
    }

    int destination_fd = open(destination_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (destination_fd == -1) {
        perror("Failed to open destination file");
        close(source_fd);
        return 1;
    }

    char buffer[4096];
    ssize_t bytes_read;
    ssize_t bytes_written;

    while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {
        bytes_written = write(destination_fd, buffer, bytes_read);
        if (bytes_written == -1) {
            perror("Failed to write to destination file");
            close(source_fd);
            close(destination_fd);
            return 1;
        }
    }

    if (bytes_read == -1) {
        perror("Failed to read from source file");
        close(source_fd);
        close(destination_fd);
        return 1;
    }

    close(source_fd);
    close(destination_fd);

    printf("File copied successfully.\\n");

    return 0;
}

在这个示例中,你需要将/path/to/source/file替换为源文件的实际路径,并将/path/to/destination/file替换为目标文件的实际路径。该程序会打开源文件和目标文件,并通过循环从源文件中读取数据,并将数据写入目标文件中,直到源文件的数据被完全复制。然后关闭文件描述符,并输出成功的消息。

如果你希望使用C++编写代码,你可以在上面的示例中添加适当的#include语句,并将代码放在main函数内。例如:

#include <iostream>
#include <fstream>

int main() {
    const std::string source_file = "/path/to/source/file";
    const std::string destination_file = "/path/to/destination/file";

    std::ifstream source(source_file, std::ios::binary);
    if (!source) {
        std::cerr << "Failed to open source file" << std::endl;
        return 1;
    }

    std::ofstream destination(destination_file, std::ios::binary);
    if (!destination) {
        std::cerr << "Failed to open destination file" << std::endl;
        return 1;
    }

    destination << source.rdbuf();

    if (!destination) {
        std::cerr << "Failed to write to destination file" << std::endl;
        return 1;
    }

    std::cout << "File copied successfully." << std::endl;

    return 0;
}

这个示例使用C++的std::ifstreamstd::ofstream类来打开源文件和目标文件,并使用<<操作符将源文件中的数据复制到目标文件中。最后,输出成功的消息。

请确保在运行这些代码之前将源文件路径和目标文件路径替换为实际的文件路径。此外,还需要确保对源文件和目标文件具有适当的读写权限。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击