通过fread和fseek读取文件 [英] Reading files by fread and fseek

查看:523
本文介绍了通过fread和fseek读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用fread和fseek逐字节读取一些文件,但是使用下面的代码,它只读取前七个字节。

我怎么能让它读取34个字节?



我尝试过:



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;


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

推荐答案

您已经问过大多数相同的问题:

返回fread函数 [ ^ ]

阅读fread文档怎么样?
You already asked mostly the same question:
Return of fread function[^]
What about reading fread documentation ?


您的问题对我来说不是很清楚,但您的代码执行以下操作:



循环5次:

fseek使用SEEK_SETsets文件位置从文件开头到35

fread从该位置读取7个字节。



如果你打算读取前35个字节,你可以这样做:

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.


您正在使用 FSEEK( )在循环内,以便在读取之前始终将文件位置设置为相同的位置。这导致5次读取相同的数据。



您还必须更新搜索位置:

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

在最后一次读取数据后应始终继续读取时,您还可以将 seek()移出循环:

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


这篇关于通过fread和fseek读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆