随机访问C中的文件 [英] Random Access to file in C

查看:91
本文介绍了随机访问C中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

这可能是一个非常基本的问题,但我找不到很多.

我想读取C中的二进制文件,以便从文件中的特定位置读取特定数量的字节(随机访问).另外,我想使用win32的CreateFile/ReadFile函数来做到这一点.

我在CreateFile()中看到了FILE_FLAG_RANDOM_ACCESS标志,但是接下来呢?如何将指针设置到文件中的某个位置,然后从文件中读取特定数量的字节?

在此先谢谢您.

Hello,

This might be a very basic question, but I could not find much.

I want to read a binary file in C such that I read a particular number of bytes from a particular location in the file (random access). Also, I want to do it using CreateFile/ReadFile functions of win32.

I saw the FILE_FLAG_RANDOM_ACCESS flag in CreateFile(), but what next? How do I set the pointer to some location in the file and then read specific number of bytes from it?

Thanks in advance.

推荐答案

您不必使用Windows API进行随机文件访问.我不建议这样做,因为它是专有的,不会给您带来超过标准C/C ++库的任何好处.这是更便携式的方法:

这是使用标准C/C ++运行时库执行的操作:
http://cplus.about.com/od/learningc/ss/files.htm [ ^ ].

标准C ++库(STL, http://en.wikipedia.org/wiki/Standard_Template_Library [ http://en.wikipedia.org/wiki/Fstream [ ^ ], http://msdn.microsoft.com/en-us/library/aa365541 (v = VS.85).aspx [ http://msdn.microsoft.com/en-us/library/aa365542 (v = VS.85).aspx [
You don''t have to use Windows API for random file access. I would not recommend it because is is proprietary and does not give you any benefits over standard C/C++ libraries. Here are more portable ways of doing it:

This is how to do it using standard C/C++ run-time library:
http://cplus.about.com/od/learningc/ss/files.htm[^].

Standard C++ Library (STL, http://en.wikipedia.org/wiki/Standard_Template_Library[^]) provides object-oriented version of this API via classes istream, ostream, iostream and fstream, see http://en.wikipedia.org/wiki/Fstream[^], http://www.cplusplus.com/reference/iostream/fstream/[^]. For random access, pay attention for the members tellp, seekp, tellg and seekg.

First option is good for both C and C++, second one — naturally — required C++.


In Windows API, random access is achieved via the functions SetFilePointer and SetFilePointerEx. See:
http://msdn.microsoft.com/en-us/library/aa365541(v=VS.85).aspx[^],
http://msdn.microsoft.com/en-us/library/aa365542(v=VS.85).aspx[^].

—SA


这篇关于随机访问C中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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