我正在尝试读取数据包的标头,然后读取有效负载。但不知何故,阅读有效载荷对我来说并不适用。任何帮助都会很棒。感谢。
FILE *inputfile
struct packet {
unsigned short blocksize;
unsigned char *payload;
};
while(!feof(inputfile)) {
struct packet p;
p.payload = malloc(p.blocksize);
fread(&p, sizeof(p), 1, infp); //reads the header
fread(p.payload, sizeof(char), p.blocksize, inputfile); //reads the payload
}
答案 0 :(得分:1)
第一
fread(&p, sizeof(p), 1, infp); //reads the header
应该是
fread(&p.blocksize, sizeof(short), 1, infp); //reads the header size
然后malloc那么多
p.payload = malloc(p.blocksize);
然后读取其有效载荷
fread(p.payload, sizeof(char), p.blocksize, inputfile); //reads the payload
答案 1 :(得分:0)
以下是一些事项:
struct
声明的结束括号。malloc()
在知道块大小之前。在调用malloc()
答案 2 :(得分:0)
while(!feof(inputfile)) {
struct packet p;
fread(&p.blocksize, sizeof(short), 1, infp); //Now you got the blocksize
p.payload = malloc(p.blocksize); // Allocate memory based on blocksize
if( p.payload == NULL ) return -1 ; // Error...could not allocate mem
fread(p.payload, sizeof(char), p.blocksize, inputfile); //reads the payload
}
完成所有操作后,请确保您已完成free(p.payload) ;