Question

I have googled extensively for this and having now spent 4 hours stuck, I hope someone can help me.

I have a simple program to read a binary file, which is approx 2.7 MB. The program is compiled on Windows using the tcc compiler. I'm experienced in various high level languages (Pascal, Modula2, Matlab, PHP, Basic) but new to C and suspect this has something to with memory allocation and variables getting overwritten.

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; 
}

In the example above I read from location 1002 in the file - this works fine - the result is:

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

Everything works as expected - the file pointer advances by 1 character for each byte read.

The issue comes for some value of the start location e.g.

start_loc = 16000

In this case the file pointer jumps in a seemingly random manner after the command e.g. i.e. read 1 byte and the file pointer moves to 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

Thanks for reading this far!

Was it helpful?

Solution

Your file is open in text mode (r) and in text mode the c++ reference says about ftell function: For text streams, the numerical value may not be meaningful but can still be used to restore the position to the same position later using fseek (if there are characters put back using ungetc still pending of being read, the behavior is undefined).

So what you get seems consistent with the doc and should not worry you.

Note that you should append a 'b' to the fopen mode if your want to open it as a binary file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top