mihirj
mihirj

Reputation: 1219

C read call buffering extra character

I am trying to read a file and send it over the network: below is my code at server for file reading and sending,

while((sent = read(fp, send_buf, BUFSIZE)) > 0)
{
    write(cssock, send_buf, strlen(send_buf));
    memset(send_buf, 0, BUFSIZE);
}

and I am reading it at client as:

while(readBytes = read(sock, file_data, BUFSIZE) > 0)
{
        write(fp, file_data, strlen(file_data));
}

file is transferred fine but I am getting an extra character at the end of buffer and my file is written as:

hello my name is abcd garbage-char

garbage-char is some arbitery character. Any idea why would I get such extra character?

note: I have double checked my file and it has nothing but the string "my name is abcd". No space, no new line. Any help is appreciated.

Upvotes: 0

Views: 1695

Answers (3)

mihirj
mihirj

Reputation: 1219

Actual cause of the problem was the POSIX read() API. It does not return a NULL terminated string which was stuffing garbage characters in the buffer.

What I did to solve this problem is below:

while((sent = read(fp, send_buf, BUFSIZE - 1)) > 0)
{
    if(sent < BUFSIZE)
       send_buf[sent] = '\0';
    else
       send_buf[BUFSIZE] = '\0';

    write(cssock, send_buf, strlen(send_buf));
    memset(send_buf, 0, BUFSIZE);
}

and it solved it. Thank you all for your help though.

Upvotes: 2

Zan Lynx
Zan Lynx

Reputation: 54355

The solution here is simple. Use the length of the data you received, not the length of the string. You did not receive a "string". You received an arbitrary block of bytes which can be any value from 0 to 255. So strlen may return useless results. But the number of bytes read is always accurate.

Upvotes: 3

yanchong
yanchong

Reputation: 376

I suggest you print your send_buf in your server and your file_data in the client see whether they are same. And also a suggestion, use memset(send_buf, 0, BUFSIZE) before you read your file in server, and memset(filedata, 0, BUFSIZE) before you read from socket in client.

Upvotes: 1

Related Questions