【发布时间】: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 的良好开端。