I’m writing a small sockets program (GNU libc). I have a loop which asks user for input (e.g. “MSG> “). When the user presses enter the message is sent (currently to a server on localhost).
Anyway, I want to read from stdin into a char buffer[256]. I’m currently using fgets() which doesn’t do what I want. I’m not sure how write the code such that I ask the user and then get data 256 -1 bytes at a time so that I can send a c-string of 1000 bytes via several strings of 256 bytes.
EDIT: Add code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 256
int main(int argc, char *argv[])
{
char msg[BUFSIZE];
size_t msgLen;
msgLen = strlen(fgets(msg, BUFSIZE, stdin));
puts(msg);
// This simply checks whether we managed to fill the buffer and tries to get
// more input
while (msgLen == (BUFSIZE - 1))
{
memset (msg, '\0', BUFSIZE);
fread(msg, BUFSIZE, 1, stdin);
msg[BUFSIZE - 1] = '\0';
msgLen = strlen(msg);
puts(msg);
if (msgLen < (BUFSIZE - 1))
break;
}
return 0;
}
You’re implementing a loop to ensure 1000 bytes are recieved, right? The loop should indicate that it’s counting up to 1000, for the sake of legibility. Keep track of the number of bytes you read (using the += operator), and use that number in the loop condition.
You seem to assume that
freadwill read 255 bytes, but this is under the invalid assumption that 255 bytes are available. When less than 255 bytes are read, this doesn’t necessarily indicate an error; keep reading! When the return value offreadis less than zero, then you should be worried. Make sure you handle those situations.