本文介绍了在C程序设计FREAD功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于C的 FREAD 函数的两个问题:


  1. 我已阅读, FREAD 是用来读取二进制文件。然而,当我读到一个二进制文件与fgets 使用阅读模式R并用文本文件 FREAD 使用RB模式,结果是一样的阅读文本文件与fgets FREAD 。那么,为什么会有不同的函数来读取二进制和文本文件?


  2. 我使用 FREAD 读10个字节的文件在一个电话。我应该怎么停在文件的结尾读 - 即如何 EOF FREAD



解决方案

1问题答案>

1> FREAD

 为size_t FREAD(无效* PTR,为size_t长度size_t计数,FILE *流);

从数据流中读取块(试图理解这一点)

读取计数元件的阵列,每一个的尺寸大小的字节,从流并将它们存储在由ptr指定的内存块。
流的现在的位置指示器的字节读出的总量推进。
字节如果成功读取的总金额为(尺寸*计)。

2>与fgets

 字符*与fgets(字符* STR,INT NUM,FILE *流);

从流获取字符串(试图理解这一点)

从流中读取字符,并将它们存储为一个C字符串str中,直到被读取或达到或者换行或将档案结尾(NUM-1)的字符,以先到者为准。
换行符使得与fgets停止阅读,但它被认为是一种有效的字符,因此它被包含复制到str中的字符串中。
字符阅读信号的C字符串结束后一个空字符自动str中追加。


第二个问题中的答案
在FREAD返回值为

成功地读出被返回作为一个为size_t对象,它是一个完整的数据类型的元素的总数。
如果这个数字不同于计数参数,或者发生错误或文件结束为止。

您可以使用FERROR或的feof检查是否发生错误或达到了档案结尾。

I have two questions about C's fread function:

  1. I have read that fread is used to read a binary file. However, when I read a binary file with fgets using read mode "r" and a text file with fread using "rb" mode, the results are the same as reading a text file with fgets and a binary file with fread. So, why are there different functions for reading binary and text files?

  2. I am using fread to read 10 bytes of a file in one call. How should I stop reading at the end of file – i.e. how is EOF specified in fread?

解决方案

answer of 1 question >

1>fread

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Read block of data from stream (try to understand this)

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.The postion indicator of the stream is advanced by the total amount of bytes read.The total amount of bytes read if successful is (size * count).

2>fgets

char * fgets ( char * str, int num, FILE * stream );

Get string from stream (try to understand this)

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.A null character is automatically appended in str after the characters read to signal the end of the C string.


answer of 2nd questionin fread return value is

The total number of elements successfully read is returned as a size_t object, which is an integral data type.If this number differs from the count parameter, either an error occured or the End Of File was reached.

You can use either ferror or feof to check whether an error happened or the End-of-File was reached.

这篇关于在C程序设计FREAD功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:21