繁体   English   中英

c 多个文件描述符

[英]c multiple file descriptors

我正在尝试制作一个 C 程序,该程序将两个文件的内容连接到一个目标文件中。 为此,我必须同时打开至少 2 个文件,但我不知道为什么我不能。 下面的两段代码可以充分描述这个问题:

为什么这样做:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    void * buf;
    int bytes;
    while ((bytes = (int)read(fdes, buf, 3)) > 0) {
        printf("%s", (char*)buf);
    }
    close(fdes);
    return 0;
}

这不是吗?

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    size_t fdes2 = open(argv[2], O_RDONLY);
    void * buf;
    int bytes;
    while ((bytes = (int)read(fdes, buf, 3)) > 0) {
        printf("%s", (char*)buf);
    }
    close(fdes);
    close(fdes2);
    return 0;
}

我不能打开多个文件吗?

我做了一些改变,这有效:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    size_t fdes2 = open(argv[2], O_RDONLY);
    size_t length = 0;
    char * buf = (char *)malloc(sizeof(char) * length);
    int bytes;

    while ((bytes = (int)read(fdes, buf, sizeof(buf) - 1)) > 0) {
        printf("%s", buf);
    }

    while ((bytes = (int)read(fdes2, buf, sizeof(buf) - 1)) > 0) {
        printf("%s", buf);
    }
    close(fdes);
    close(fdes2);
    return 0;
}

首先, buf应该是char *

其次,您需要将buf某个地方( mallocchar array

参考: https : //www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/rtrea.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM