开发者

Qt/C++ How to position in the middle of a file (offset) -> only known is filesize

开发者 https://www.devze.com 2023-03-27 10:29 出处:网络
Hy all, in Qt i have: FILE *pInFile = fopen(strFileName.toLatin1().constData(), \"r\"); QFileInfo fi(strFileName);

Hy all, in Qt i have:

FILE *pInFile = fopen(strFileName.toLatin1().constData(), "r");
QFileInfo fi(strFileName);
qint64 fileSize = fi.size();

//GO TO THE MIDDLE
//WHAT IS THE POSITION OF THE MIDDLE (INTEGER)

Instead of reading trough the whole file (fgets) in a loop, i want to know开发者_运维问答 the offset of the middle of the file. And based on that offset i want to get that position.

Basically;

  • get offset from a file based on my given bytes (example: fileSize/2)
  • based on that offset what is the position (row index)

Is it possible to have something like this for determining position? int centerPos = ftell(Offset middle, pInFile);

I don't think i'm on the right path here, can u give some advice?

Thx

ps.

And would be nice to position on the the beginning of the position


Use QFile instead of a raw file pointer. It has a seek method.

http://doc.qt.nokia.com/latest/qfile.html#seek

You can determine the middle of the file using

QFile myfile("filename");
int middle = myfile.size() /2;

...then, as mentioned, start reading at that position after calling

myfile.seek(middle).


  • Open the file in append mode.
  • do ftell() to know the end position of file.
  • Calculate middle of file by halving step 2, and store it in a variable named middle.
  • Then define the following function

    void middle_fseek(FP* FilePointer, int offset)

    {

    fseek(FilePointer, middle+ offset, SEEK_SET);

    }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号