Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
i use fread and fseek to read some file byte by byte, but with the following code , it reads only the the first seven bytes.
how can i let it read 34 bytes?

What I have tried:

static FILE *fp;

static int u32FilePointer=35;
for(i = 0; i < 5; i++)
       {
         fseek(fp, u32FilePointer, SEEK_SET);
         u16BytesRead = fread(u8Buffer, 1, 7, fp);
         printf("u32FilePointer : %lu\n" ,u32FilePointer);
Posted
Updated 1-Mar-20 1:36am

You already asked mostly the same question:
Return of fread function[^]
What about reading fread documentation ?
 
Share this answer
 
Comments
BaselAla 25-Apr-18 9:27am    
i am sorry for that , but when i excute it i find some strange things.
thank you (:
Your question isn't quite clear to me, but your code does the following:

Loop 5 times:
fseek with SEEK_SETsets the file position to 35 from the beginning of the file.
fread reads 7 bytes from that position.

If you intend to read the first 35 bytes, you can just do:
fread(u8Buffer, 1, 35, fp);


It would help if you specify how many bytes you want to read from which position in the file.
 
Share this answer
 
You are using fseek() within the loop so that the file position is always set to the same position before reading. That results in reading the same data 5 times.

You have to update the seek position too:
for(i = 0; i < 5; i++)
{
    fseek(fp, u32FilePointer, SEEK_SET);
    u16BytesRead = fread(u8Buffer, 1, 7, fp);
    // The read updates the internal position of the file pointer
    // If we want to track the position we have to do it also for our variable
    u32FilePointer += u16BytesRead;
    // Or use ftell() to get the internal position
    //u32FilePointer = ftell(fp);
    printf("u32FilePointer : %lu\n" ,u32FilePointer);
}
When reading should always continue after the last read data, you can also move the seek() out of the loop:
fseek(fp, u32FilePointer, SEEK_SET);
for(i = 0; i < 5; i++)
{
    u16BytesRead = fread(u8Buffer, 1, 7, fp);
    printf("u32FilePointer : %lu\n", ftell(fp));
}
 
Share this answer
 
Comments
BaselAla 25-Apr-18 9:29am    
that is clear now , i thank you very much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900