【发布时间】:2023-11-16 17:28:01
【问题描述】:
底部的解决方案
我正在开发一个 IP 转发程序。读取一个头域后,我使用fseek() 将文件指针指向下一个IP 头域的开头。只是,我的当前位置值为 20,偏移量为 40,但当我 fseek() 时,它停留在字节数 20。
struct line {
unsigned char a;
unsigned char b;
unsigned char c;
unsigned char d;
};
struct line l1;
long datagram_length = 0;
int current_position = 0;
ip_packets = fopen("ip_packets", "r+");
fread(&l1, 4, 1, ip_packets);
header_length = l1.a & 0x0f;
header_length *= 4;
printf("Header length = %u\n", header_length);
datagram_length = l1.c * 256 + l1.d;
printf("Datagram length = %d\n", datagram_length);
printf("Current position = %d\n", current_position);
current_position += header_length;
fseek(ip_packets, datagram_length, current_position);
current_position += datagram_length;
printf("Current position = %d\n", current_position);
long pos;
pos = ftell(ip_packets);
printf("pos is %ld bytes\n", pos);
打印出来:
Header length = 20
Datagram length = 40
Current position = 20
Current position = 60
pos is 20 bytes
上面的代码包括我对fseek() 函数的变量初始化。我尝试使用SEEK_CUR 作为int whence 参数,但随后程序不会终止。文件结尾永远不会到达,运行一秒钟后我得到pos is 234167456 bytes,文件只有 377 字节。
更新
显然你应该以r+ 模式打开文件,所以我已经更新了它,但它仍然在做同样的事情
ip_packets = fopen("ip_packets", "r+");
也试过rb模式
解决方案
我的解决方案是循环字节数并在每个循环内调用fgetc()。不合适,但它有效
【问题讨论】: