Home > database >  Read file lines into one string seperated by \r\n
Read file lines into one string seperated by \r\n

Time:11-03

I need to read a file that looks like

foo
bar
foobar
barfoo

in C and save it to a char buf[] that looks like "foo\r\nbar\r\nfoobar\r\nbarfoo\r\n"

Currently I am trying to use fgets() but im not sure how I can add the \r\n into the char[] that I have

void client(char* server_host) {
    int rc, client_socket;
    char buf[BUFFER_LEN];
    client_socket = connect_to_server(server_host, NON_RESERVED_PORT);
    printf("\nEnter a line of text to send to the server or EOF to exit\n");
    while(fgets(buf, BUFFER_LEN, stdin) != NULL) {
        send_msg(client_socket, buf, strlen(buf)   1);
        rc = recv_msg(client_socket, buf);
        buf[rc] = '\0';
        printf("client received %d bytes  :%s: \n", rc, buf);
        printf("\nEnter a line of text to send to the server or EOF to exit\n");
    }
}

This is the way I'm trying to do this, but when I use the send_msg() I need the buf that I'm using to be seperated by the \r\n delimeter on each line that I read in.

CodePudding user response:

A hacky, yet minimal code.

char buf[BUFFER_LEN];

// Read up to 2 less to be sure we have room for an added \r\n
while(fgets(buf, BUFFER_LEN - 2, stdin)) {

  // Use strcspn() to find offset of \n if it exists or the string length
  // Then write \r\n\ there
  strcpy(buf   strcspn(buf, "\n"), "\r\n");

  // send it
  send_msg(client_socket, buf, strlen(buf));
}

CodePudding user response:

Sounds like you're saying you have a buffer buf that contains something like

{ 'a', 'b', 'c', '\n', 0 }
{ 'a', 'b', 'c', 0 }            // In the case of a line that's longer than BUF_SIZE-1.

But you want a buffer that contains

{ 'a', 'b', 'c', '\r', '\n' }   // send_msg doesn't care about the NUL.
{ 'a', 'b', 'c' }

It's just a question of checking if the last character is a LF, and replacing the LF and NUL with CR and LF.

...
while (fgets(buf, BUFFER_LEN, stdin) != NULL) {
    size_t len = strlen(buf);
    if (buf[len-1] != '\n') {
       // The line didn't fit in the buffer.
       send_msg(client_socket, buf, len);
       continue;
    }

    buf[len-1] = '\r';
    buf[len] = '\n';
      len;
    send_msg(client_socket, buf, len);

    ...
}
...

This code doesn't handle NULs entered by the user well. It's GIGO situation as far as this answer is concerned.

  •  Tags:  
  • c io
  • Related