【问题标题】:C: fseek() not pointing to the defined Byte numberC: fseek() 没有指向定义的字节数
【发布时间】: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()。不合适,但它有效

【问题讨论】:

    标签: c file ip forward fseek


    【解决方案1】:

    你的变量current_position的定义是什么?

    您对 fseek 的使用似乎是错误的。 fseek(3) 的手册页说定义是:

    fseek(FILE *stream, long offset, int whence);

    对于您的用例,whence 必须设置为在stdio.h 中定义的常量SEEK_CUR

    【讨论】:

    • 我忘了包括变量初始化——它们已被添加。我以为我也应该使用SEEK_CUR,但是文件永远不会到达末尾。我让它运行一秒钟,得到pos is 234167456 bytes,文件只有377字节。程序不会终止
    • 修复一个错误后遇到另一个错误并不罕见。