c - 使用 read() 将文件内容写入屏幕和 C 中的其他文件的问题

标签 c linux file operating-system

我正在尝试将一个文件的内容复制到另一个文件。我还想在屏幕上显示文件的内容,如果可能的话,我想使用系统调用(写入)来完成所有这些工作。

这是我的代码

#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 循环之外添加 readwrite 及其单独的缓冲区和 ssize_t .

是什么导致了这个问题?

最佳答案

在这条线上我想你想要fd2写入副本文件。

另请注意运算符优先级,<优先级高于 && .在与 < 比较之前,将写入调用括在括号中以评估这些调用运营商。

   if((write(fd2,buf,nread) && write(1,buf,nread)) < nread )

关于c - 使用 read() 将文件内容写入屏幕和 C 中的其他文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255646/

相关文章:

java - JAVA如何在linux中获取java.lang.Process的PID

c++ - 是否可以将二进制文件存储在 exe 中

file - unix 将尾部重定向到文件

objective-c - Objective C : How do I read a string from a file containing a list of strings delimited by/n, 然后分别存储字符串的每个字符

linux - 在 ubuntu 和 nginx 上托管多个 ASP NET Core 站点作为反向代理

c - Windows 上的共享内存可以由单独的进程访问(读取和写入)

c - C 中的二叉搜索树,段错误

c - 显示单链表的元素

linux - 为什么这个 cron 作业每分钟运行一次?

c - fscanf 没有正确读取 double