简体   繁体   中英

Using a pipe as a stream C

First time I ask for help here.

I'm currently programming a game in C and for the network part I'm transmitting a string. To analyse this and get back the different int printed in it, I want to use a stream. Since I found no stream in C, I am using 'pipe' and fdopen to transform it to a File stream.

I was doing it like that at first :

int main (){
    int fdes[2], nombre;
    if (pipe(fdes) <0){
        perror("Pipe creation");
    }
    FILE* readfs = fdopen(fdes[0], "r");
    FILE* writefs = fdopen(fdes[1], "a");
    fprintf(writefs, "10\n");
    fscanf(readfs, "%d", &nombre);
    printf("%d\n", nombre);
    return 0;
}

But it's not working. A functional way is to use write instead of fprintf and this is working :

int main (){
    int fdes[2], nombre;
    if (pipe(fdes) <0){
        perror("Pipe creation");
    }
    FILE* readfs = fdopen(fdes[0], "r");
    write(fdes[1], "10\n", 3);
    fscanf(readfs, "%d", &nombre);
    printf("%d\n", nombre);
    return 0;
}

I found a solution to my problem but I still want to understand why the first solution wasn't working. Any idea ?

It's caused by stream buffering. Add fflush(writefs); after the call to fprintf .

 fprintf(writefs, "10\n");
 fflush(writefs);
 fscanf(readfs, "%d", &nombre);

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