0

我为此进行了广泛的谷歌搜索,现在已经卡住了 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

感谢您阅读到这里!

4

1 回答 1

1

您的文件在文本模式 (r) 和文本模式下打开,c++ 参考说明 ftell 函数:对于文本流,数值可能没有意义,但仍可用于稍后使用 fseek 将位置恢复到相同位置(如果使用 ungetc 放回的字符仍有待读取,则行为未定义)。

所以你得到的似乎与文档一致,不应该让你担心。

请注意,如果您想将 fopen 模式作为二进制文件打开,则应在 fopen 模式后附加一个“b”。

于 2014-02-21T21:45:56.287 回答