I need to read a file and then send it through a socket, but fread crash for some reason. Any idea?
//Get file length
fseek(fd, 0, SEEK_END);
int fileLen=ftell(fd);
fseek(fd, 0, SEEK_SET);
//Allocate memory
buf=(char *)malloc(fileLen+1)* sizeof(char));
if (!buf)
{
fprintf(stderr, "Memory error!");
}
rewind(fd);
fread((void *)buf, strlen(buf)+1, 1, fd);
There are quite a few basic confusions in that code.
ftell()
returns long
, not int
. Also it should be const
, since the file's size is assumed not to change while we read it. rewind()
and use fseek()
to offset 0. malloc()
in C . sizeof (char)
, that's always 1. void *
in fread()
, that's completely pointless. fread()
, calling strlen()
on an undefined pointer is undefined behavior. fread()
succeeds. fread((void *)buf, strlen(buf)+1, 1, fd);
should be
fread((void *)buf, 1, fileLen, fd);
You did not initialized the contents of buf
, so strlen(buf)
will not return the correct length of buf
.
By the way, buf=(char *)malloc(fileLen+1)* sizeof(char));
should be buf=(char *)malloc(fileLen);
, there is no need to allocate that extra byte, and sizeof(char)
always returns 1.
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.