小编The*_*oom的帖子

使用标准 I/O 和系统调用制作文件副本的 C 程序

我正在尝试编写一个 C 程序,它使用标准 I/O 和系统调用来执行将一个文件的内容复制到另一个文件。

到目前为止,我已经这样做了:

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

int main(int argc, char *argv[])
{
    int fd1, fd2;
    char buffer[1024];
    long int n1;

    if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC, 0700)) == -1)){
        perror("file problem");
        exit(1);
    }

    while((n1=read(fd1, buffer, 1024) > 0)){
        if(write(fd2, buffer, n1) != n1){
            perror("writing problem ");
            exit(3);
        }
    }
    close(fd1);
    close(fd2);
}
Run Code Online (Sandbox Code Playgroud)

当我像这样运行程序时:

cc copyContents.c 
./a.out one.txt two.txt
Run Code Online (Sandbox Code Playgroud)

假设one.txt定义明确,我想要的是创建一个名为的新文件two.txt并复制所有内容one.txt

当我查看two.txt运行程序后的内容时,它实际上什么都没有。只是一个空白文件。

我哪里错了?

c unix linux

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

c ×1

linux ×1

unix ×1