我怎样才能从一个目录拷贝一个文件到另一个C / C ++ [英] How can I copy a file from one directory to another in c/c++

查看:189
本文介绍了我怎样才能从一个目录拷贝一个文件到另一个C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找关于如何将文件从一个目录复制到另一个在C程序应该只使用跨平台的功能是本机到C一个简单的例子。

I am looking for a simple example on how to copy a file from one directory to another in C. The program should only use cross platform functions that are native to C.

推荐答案

下面是一个简单的未经检验的C程序,做你所需要的:

Here is a simple untested C program that does what you need:

#include <stdio.h>

int main(int argn, char * argv[]) {

    int src_fd, dst_fd, n, err;
    unsigned char buffer[4096];
    char * src_path, dst_path;

    // Assume that the program takes two arguments the source path followed
    // by the destination path.

    if (argn != 3) {
        printf("Wrong argument count.\n");
        exit(1);
    }

    src_path = argv[1];
    dst_path = argv[2];

    src_fd = open(src_path, O_RDONLY);
    dst_fd = open(dst_path, O_CREAT | O_WRONLY);

    while (1) {
        err = read(src_fd, buffer, 4096);
        if (err == -1) {
            printf("Error reading file.\n");
            exit(1);
        }
        n = err;

        if (n == 0) break;

        err = write(dst_fd, buffer, n);
        if (err == -1) {
            printf("Error writing to file.\n");
            exit(1);
        }
    }

    close(src_fd);
    close(dst_fd);
}

这篇关于我怎样才能从一个目录拷贝一个文件到另一个C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆