【问题标题】:why this c program for copying a file is not working correctly?为什么这个用于复制文件的 c 程序不能正常工作?
【发布时间】:2021-08-22 09:49:14
【问题描述】:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int fd1 = open(argv[1], O_RDONLY); 
    int fd2 = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0700);

    if (fd1 == -1 || fd2 == -1) {
        perror("cannot open file");
        exit(-1);
    }
    
    char buffer[100];
    int n;
    while (n = read(fd1, buffer, 100) > 0) { // not working
        write(fd2, buffer, n);
    }
    
    close(fd1);
    close(fd2); 
    return 0;   
}

我正在尝试编写一个将一个文件的内容复制到另一个文件的 C 程序。 我认为 while 循环中的读取存在问题,但我不确定。

【问题讨论】:

  • 如果您在编译时打开了一组健康的警告,则应该向您指出问题。 -Wall -Wextra 是 gcc 和 clang 的良好开端。

标签: c file cp


【解决方案1】:
while( n = read( fd1, buffer, 100) > 0)

这是不正确的,因为它将read( fd1, buffer, 100) &gt; 0 的结果分配给n。这是因为&gt; 的优先级高于=

为了纠正这个使用括号:

while((n = read( fd1, buffer, 100)) > 0)

【讨论】:

    【解决方案2】:

    切勿在条件内使用赋值。这是一种获取与运算符优先级、副作用、错误输入 == 等相关的各种错误的非常简单的方法。

    在您的情况下,错误是 &gt; 的优先级高于 =

    在这种情况下,代码可以重写为:

    int n;
    while(1)
    {
      n = read(fd1, buffer, 100);
      if(n==0)
        break;
    
      if(write(fd2, buffer, n) != n)
      { 
        /* handle errors */ 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 2020-09-19
      • 2012-04-01
      • 2020-03-18
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多