将一个文件复制到另一个(Unix/C)? [英] Copying one file to another(Unix/C)?

查看:45
本文介绍了将一个文件复制到另一个(Unix/C)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来将一个文件复制到另一个文件.尽管该代码有效,但该代码仍会打印两个错误消息.为什么是这样 ?我是 Unix 和 C 编程的完整初学者(尽管我之前曾使用过 C++),因此任何尽可能详细的帮助都会很棒.谢谢!

I have written the following code to copy one file to another. Although the code works, the code still prints both error messages. Why is this ? I am a complete beginner to Unix and C programming(although I have worked with C++ before), so any help in as much detail as possible would be great. Thanks !

int main(int argc, char *argv[])
{
    int n;
    char buf[4096];
    while ((n=read( open(argv[1], O_RDONLY) , buf, 4096))>0)
    {
        if (write(creat(argv[2], S_IREAD | S_IWRITE ), buf, n)!=n)
            printf("Error writing to file.\n");
    }
    if (n<0)
        printf("Error reading from file.\n");
    exit(0);
}

推荐答案

您在每次迭代中打开文件并尝试在每次迭代中创建该文件.

You are opening the file in each iteration and attempt to creat the file in each iteration.

因此,除了第一次迭代之外,所有后续写入都将失败.它可能似乎有效",因为您的输入文件包含少于 4096 个字节.所以第一个 write 调用是让它看起来好像所有东西都被复制了.如果使用超过 4096 个字节的输入,您将只看到前 4096 个字节(假设 read()write() 都没有失败).

So except the very first iteration, all subsequent writes will fail. It probably "seems to work" because your input file contains less than 4096 bytes. So the first call to write was to make it look like everything was copied. If use an input which has more than 4096 bytes, you'll see only the first 4096 bytes (assuming both read() and write() don't fail).

如果 write() 一直成功(例如,你有 creat() 在循环之外),那么 open()> 调用不断打开同一个文件,这可能是一个无限循环,否则您的系统将耗尽文件描述符并返回无效的文件描述符,并且 read() 将失败.

If write() were to succeed all the time (e.g. you had the creat() outside the loop) then the open() call continuously opens the same file and is potentially an infinite loop or your system would run out of file descriptor and return an invalid file descriptor and read() will fail on that.

长话短说:不要编写那样的代码:)

Long story short: don't write code like that :)

将调用 open()creat() 移到循环外:

Move both calls to open() and creat() outside the loop:

int fd = open(argv[1], O_RDONLY);
if (fd == -1) { 
   perror("open");
   exit(1);
}

int fd2 = creat(argv[2], S_IREAD | S_IWRITE );
if (fd2 == -1) { 
   perror("write");
   exit(1);
}

while ( (n=read( fd , buf, 4096)) > 0 )
{
    if ( write(fd2 , buf, n) != n )
        printf("Error writing to file.\n");
}

这篇关于将一个文件复制到另一个(Unix/C)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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