Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 3552

Troubleshooting • Re: C++ fgets behaving very oddly on Bookworm (no other environment tested yet)

$
0
0

Code:

      std::stringstream msgsst;          // stringstream to accumulate the input message      char bufl;                                       // last character in current fgets read buffer      do{                                                 // loop til you get a \n            char msgbuf[msglen];          // fgets read buffer            int len;                                     // number of characters read            fd = fopen(fifoname, "r");     // open the fifo            fgets(msgbuf, msglen, fd);  //read til \n, buffer full or EOF            fclose(fd);                               // close the fifo            len = strlen(msgbuf);            // find number of characters read            bufl = msgbuf[len-1];             // find the last character            msgsst << msgbuf;               // build up to complete input stringstream                         } while (bufl != '\n');                   // keep going til you have a \n
Your code exits the do loop after reading the first line. It will read the first line and discard the rest because you are closing the file. The fopen function is buffered I/O and will read all the lines in and discard them when fclose is called.

I tried the following pair of programs on my Pi 5, running Bookworm.

C code "server" side program.

Code:

#include <stdio.h>int main(){    FILE *fp = fopen("/tmp/my_named_pipe", "w");    if (fp)    {        fprintf(fp, "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n");    }    fclose(fp);    return 0;}
C++ "client"

Code:

#include <cstdio>#include <cstring>#include <iostream>int main(){    FILE *fp = fopen("/tmp/my_named_pipe", "r");    if (fp)    {        char msgbuf[1024];        while (fgets(msgbuf, sizeof(msgbuf), fp))        {            printf("Received %s", msgbuf);        }        fclose(fp);    }    return 0;}
Output of client.cxx is

Code:

Received oneReceived twoReceived threeReceived fourReceived fiveReceived sixReceived sevenReceived eightReceived nineReceived ten

Statistics: Posted by AndyD — Sun Feb 11, 2024 11:01 am



Viewing all articles
Browse latest Browse all 3552

Trending Articles