我为此进行了广泛的谷歌搜索,现在已经卡住了 4 个小时,我希望有人可以帮助我。
我有一个简单的程序来读取大约 2.7 MB 的二进制文件。该程序是在 Windows 上使用 tcc 编译器编译的。我在各种高级语言(Pascal、Modula2、Matlab、PHP、Basic)方面经验丰富,但对 C 来说是新手,我怀疑这与内存分配和变量被覆盖有关。
void main ()
{
long int start_loc;
long int actual_loc;
int seek_result;
char file_to_process[]="d:/tmp/pfc/test.out";
char read_int;
int spaces;
int read_result;
FILE *data_file;
//fpos_t position;
data_file=fopen(file_to_process,"r");
if (data_file == NULL) {
printf("Error");
}
start_loc = 1002;
printf("\n size of start_loc : %d",sizeof(start_loc));
actual_loc = ftell(data_file);
printf("\nBEFORE location %d \n",actual_loc);
seek_result = fseek(data_file, start_loc, SEEK_SET); //move to start of search location in the file
actual_loc = ftell(data_file);
printf("\n AFTER seek location %d \n",actual_loc);
fread(&read_int, 1, 1, data_file);
actual_loc = ftell(data_file);
printf("\n AFTER read location %d \n",actual_loc);
printf("\n read result %x" ,*&read_int);
fread(&read_int, 1, 1, data_file);
actual_loc = ftell(data_file);
printf("\n AFTER read location %d \n",actual_loc);
printf("\n read result %x" ,*&read_int);
fclose(data_file);
return;
}
在上面的示例中,我从文件中的位置 1002 读取 - 这工作正常 - 结果是:
size of start_loc : 4
BEFORE location 0
AFTER seek location 1002
AFTER read location 1003
read result 0
AFTER read location 1004
read result 3
一切都按预期工作 - 文件指针每读取一个字节就前进 1 个字符。
问题在于起始位置的某些值,例如
start_loc = 16000
在这种情况下,在命令 egie 读取 1 个字节后,文件指针以看似随机的方式跳跃,并且文件指针移动到 19586。
size of start_loc : 4
BEFORE location 0
AFTER seek location 16000
AFTER read location 19585
read result 47
AFTER read location 19586
read result 0
感谢您阅读到这里!