为什么这个用于复制文件的C程序不能正常工作?
#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 循环中的读取有问题,但我不确定。
回答
while( n = read( fd1, buffer, 100) > 0)
这是不正确的,因为它分配了read( fd1, buffer, 100) > 0into的结果n。发生这种情况是因为>具有比 更高的优先级=。
要更正此问题,请使用括号:
while((n = read( fd1, buffer, 100)) > 0)