-2

I'm working on a project using UDP protocol to transfer a file, but when I use strcpy() to copy a buffer into another string, it always missing some characters.

The simple idea is that: I defined a struct:

struct frame{
    int kind;//transmission(0) or retransmission(1)
    int seq;
    int ack;
    char info[256];
};

Then I use fread to get the content of a text file into the buffer:

char buffer[256] = {0};
fread(buffer, 256, 1, fp);//read file: 256 byte
struct frame currFrame;
currFrame.ack = 0;

bzero(currFrame.info, 256);
strcpy(currFrame.info, buffer); //store the content to transfer
printf("%s\n", buffer);
printf("%s\n", currFrame.info);

The code above is in a for loop because i read file multiple times.

when I use printf(), half time, the result is right. But half time, they are different(like missing some characters in the head). How can I fix this?

The output is attached(The above is buffer, which is right):

enter image description here

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
user419050
  • 41
  • 2
  • 6

1 Answers1

4

The strcpy function is only for strings. To copy arbitrary data, use memcpy. Also, the %s format specifier is only for strings. Functions like fread read arbitrary binary data and don't try to form strings.

Also, you called fread in such a way that it won't tell you how many bytes it actually read. Unless you're positive you're always going to read exactly 256 bytes, that isn't smart. Instead, set the second parameter of fread to 1 and use the third parameter to set the maximum number of bytes to read. And don't ignore the return value -- that's how you know how many bytes it was actually able to read.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thanks. But sorry I still don't get it, You can see that when i print buffer, it works fine, so i think fread() work right. Since buffer is string, info who is in struct is also defined as string, so strcpy() should work. – user419050 Nov 27 '17 at 21:09
  • @user419050 Why do you think buffer is a string after `fread` returns? The `fread` functions is not a string function. – David Schwartz Nov 28 '17 at 16:33