我正在尝试将一个文件的内容复制到另一个文件。我还想在屏幕上显示文件的内容,如果可能的话,我想使用系统调用(写入)来完成所有这些工作。
这是我的代码
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define PERMS 0644
char *workfile = "file1.txt";
char *workfile2 = "file2.txt";
int main(int argc, char *argv[])
{
int fd;
int fd2;
int fd3;
ssize_t nread0;
ssize_t nread;
char buf[1024];
char buf2[1024];
ssize_t nread2;
const char msg[] = "File 3 contains:";
if ((fd= open(workfile, O_RDWR,PERMS)) == -1) {
printf("Couldn't open %s\n", workfile);
exit(1);
}
if ((fd2 = open(workfile2,O_RDWR,PERMS)) == -1) {
printf("Couldn't open %s\n",workfile2);
exit(1);
}
while (nread =read(fd,buf,1024)) {
if (lseek(fd2,0,SEEK_END) < 0) return 1;
if (write(fd,buf,nread) && write(1,buf,nread) < nread) {
close(fd);
close(fd2);
return(-3);
}
}
close(fd);
if (nread ==-1) {
return (-4);
}
return 0;
}
当我也尝试写入屏幕时,file1
的内容不会复制到 file2
,但 file1
的内容是写入屏幕。
我还尝试在 while
循环之外添加 read
和 write
及其单独的缓冲区和 ssize_t
.
是什么导致了这个问题?
最佳答案
在这条线上我想你想要fd2
写入副本文件。
另请注意运算符优先级,<
优先级高于 &&
.在与 <
比较之前,将写入调用括在括号中以评估这些调用运营商。
if((write(fd2,buf,nread) && write(1,buf,nread)) < nread )
关于c - 使用 read() 将文件内容写入屏幕和 C 中的其他文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255646/