简体   繁体   English

使用fread功能:要读取的大小大于可读取的大小

[英]Using fread function: size to be read is greater than available for reading

I have a question: 我有个问题:

I am using fread to read a file. 我正在使用fread来读取文件。

typedef struct {
    int ID1;
    int ID2;
    char string[256];
} Reg;

Reg *A = (Reg*) malloc(sizeof(Reg)*size);

size = FILESIZE/sizeof(Reg);

fread (A, sizeof(Reg), size, FILEREAD);

Using a loop, consecutively call this call, to make me read my entire file. 使用循环,连续调用此调用,让我读取整个文件。

What will happen when I get near the end of the file, and I can not read "size" * sizeof (Reg), or if you are only available to read half this amount, what will happen with my array A. It will be completed? 当我接近文件的末尾会发生什么,我无法读取“size”* sizeof(Reg),或者如果你只能读取这个数量的一半,那么我的数组A会发生什么。它会是完成? The function will return an error? 该函数将返回错误?

Knowing how the file was read by the fread through? 知道如何通过fread读取文件?

Edi1: Exactly, if the division is not exact, when I read the last bit smaller file size that I'll read things that are not on file, I'm wondering with my vector resize to the amount of bytes that I can read, or develop a dynamic better. Edi1:确切地说,如果除法不精确,当我读到最后一点较小的文件大小时,我将读取未存档的内容,我想知道我的向量调整大小到我可以读取的字节数,或者发展更好的动态。

fread returns the number of records it read. fread返回它读取的记录数。 Anything beyond that in your buffer may be mangled, do not rely on that data. 缓冲区之外的任何内容都可能被破坏,不依赖于该数据。

fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. fread返回实际读取的完整项目的数量,如果发生错误或者在到达计数之前遇到文件末尾,则可能小于计数。

The function will not read past the end of the file : the most likely occurrence is that you will get a bunch of full buffers and then a (final) partial buffer read, unless the file size is an exact multiple of your buffer length. 该函数不会读取超过文件末尾的内容:最有可能的情况是,您将获得一堆完整缓冲区,然后读取(最终)部分缓冲区,除非文件大小是缓冲区长度的精确倍数。

Your logic needs to accommodate this - the file size gives you the expected total number of records so it should not be hard to ignore trailing data in the buffer (after the final fread call) that corresponds to uninitialized records. 您的逻辑需要适应这一点 - 文件大小为您提供了预期的记录总数,因此不应该忽略缓冲区中的尾随数据(在最终的fread调用之后)与未初始化的记录相对应。 A 'records remaining to read' counter would be one approach. “剩余阅读记录”计数器将是一种方法。

fread() returns the number of elements it could read. fread()返回它可以读取的元素数。 So you have to check the return value of fread() to find out how many elements in your array are valid. 因此,您必须检查fread()的返回值,以找出数组中有多少元素有效。

It will return a short item count or zero if either an error occurred or EOF has is reached. 如果发生错误或达到EOF ,它将返回短项目计数或零。 You will have to use feof() ond ferror() in this case to check what condition is met. 在这种情况下,您将不得不使用feof() ond ferror()来检查满足的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM