使用C的BIN文件的Eof [英] Eof of BIN files using C

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

问题描述

你好专家,



我是使用ansi C的初学者。我习惯使用文本文件,但现在我正在尝试使用bin文件。



我设法写入bin文件,甚至使用for循环读取,但是可以在bin中读取到文件末尾吗?



这是我的示例代码。



Hello experts,

I am a beginer using ansi C. I am quite used to use text files, but now i am trying to use a bin file.

I managed to write to the bin file, and even to read using a for loop, but is it possible to read till end of file in bin please?

This is my sample code.

typedef struct
{
     char Name[name_l];
     short Score;
}player_t;

player_t Player1;

FILE *HighScores;
HighScores = fopen("HighScores.bin","rb");

fread(&Player1, sizeof(player_t),1,HighScores);
printf("\n%s\n",Player1.Name);

推荐答案

以防万一:如果用EOF表示文件结束字符,这只是一个相当愚蠢的历史字符仍然保留但几乎从未使用过,因为没有理由使用它。请参阅:

http://en.wikipedia.org/wiki/End-of -file [ ^ ]。



将文件读取到最后的方法完全取决于您需要阅读的结构。如果结构发展良好,并且您必须阅读此类结构的所有可用实例,则始终知道这些实例的数量,或者您可以从文件的总大小计算它们,或者您可以读取复杂变量-size结构顺序,但知道你已经拥有的数据的最后一块数据的确切大小。



但是假设你有更多的草率情况,当你不能预测您是否正在尝试阅读文件的实际结尾。在这种情况下,您可以从 fread 返回的结果中找出它:

http://www.cplusplus.com/reference/cstdio/fread/ [ ^ ]。



(不要对此C ++文档感到困惑:它也适用于C.)



如您所见,它返回成功读取的元素总数。如果此数字与count参数不同,则会在读取时发生读取错误或达到文件结尾。



就是这样。



-SA
Just in case: if by "EOF" you mean the End-of-file character, this is just quite a stupid historical character with is still preserved but almost never used, because there are no reasons for using it. Please see:
http://en.wikipedia.org/wiki/End-of-file[^].

The ways to read the file to the end totally depend on the structure you need to read. If the structure is well developed, and if you have to read all the available instances of such structure, you always know either the number of those instances, or you can calculate them from the total size of the file, or you can read complex variable-size structures sequentially, but know the exact size of the last chunk of data from the data you already have.

But suppose you have more sloppy situation, when you cannot predict if you are trying to read behind the actual end of file or not. In this case, you can figure out it from the result returned from fread:
http://www.cplusplus.com/reference/cstdio/fread/[^].

(Don''t get confused by this C++ documentation: it''s also applicable to C.)

As you can see, it returns the total number of elements successfully read. If this number differs from the count parameter, either a reading error occurred or the end-of-file was reached while reading.

That''s it.

—SA


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

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