简体   繁体   中英

c multiple file descriptors

I am trying to make a C program that concatenates the contents of two files at a target file. To do this I must have at least 2 files open at the same time but I haven't figured out why I can't. The problem can be sufficiently described by the two pieces of code below:

Why does this work:

#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;
}

and this doesn't?

#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;
}

can't i have multiple files open?

I make some changes, and this works:

#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;
}

First, buf should be char *

Second, you need to point buf to somewhere ( malloc or a char array )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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