简体   繁体   中英

C++ printf large buffer

The problem I am having is printf doesnt print all the data that is being returned from a client response. (verified data is being sent back via packet sniffer)

#define MAXBUFFER    24576
char buffer[MAXBUFFER];
......
datastream = read(sock,buffer,MAXBUFFER - 1);
printf("%s",buffer);
......

What is the best approach to printing all the client data to the console ... while eliminating the potential of a BOF?

Possible causes:

  1. read is not guaranteed to read all the data at once it just attempts to do so, that's why it returns the number of chars read;

  2. printf with %s will print until the first '\\0' [ASCII code 0] in your buffer.

If the buffer has any zero bytes, they will be treated as string terminators. Is this an ASCII or binary protocol? If the latter, you might want to convert to hex before printing.

1) You may need to flush stdout to get the data to display: fflush(stdout);

2) If there's a lot of data, then you probably need to use a loop to read from the socket. (If you go this route, you can probably decrease the value of MAXBUFFER, not that you necessarily have to.)

Note: Production code must also recognize when the end of a discrete message has been received -- whether by using a length count, or looking for a specific termination code, or some other means. That's not shown here. (If you use a length count, it's easy enough to sum up the values of "bytesRead" to keep track.)

// Add a byte at the end to allow for a terminating null char
char buffer[MAXBUFFER + 1];
buffer[MAXBUFFER] = '\0';
    //... 
    int bytesRead;
    while((bytesRead = read(sock, buffer, MAXBUFFER)>0)) {
        printf("%s", buffer);
int numberofbytesread = read(sock,buffer,MAXBUFFER - 1);
write(1, buffer, numberofbytesread);

You should use write(2) instead of printf, as you state you wish to send the data 'raw'. That's my understanding of your response to Dan.

Use this example to understand you requirement. Ans: Use write() if you have data with 0 or '\\0'

#include<iostream>

using namespace std;

int main()
{
    int ret=0,i;
    char buf[25470];

    for(i=0;i<25470; i++)
    {
        buf[i] = 'a';
    }

    buf[2500] = 0;

    ret = printf("%s ", buf);
    printf("\n \n Printed using 'printf' = %d \n \n", ret);

    ret = write(1,buf,sizeof(buf));
    printf("\n \n Printed using 'write' = %d \n \n", ret);

    return 0;
}

And you really need this big buffer to send a command like "ps aux" ?

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