C ++程序中的fread()函数
给出的任务是演示fread()C++的工作原理。在本文中,我们还将研究传递给fread()该函数的不同参数以及该函数返回的内容。
fread()是C++的内置函数,可从流中读取数据块。该函数计算流中每个对象的大小,每个对象的大小为“大小”字节,并将其存储在缓冲存储器中,然后位置指针前进读取的字节总数。如果成功读取的字节数将为*count。
语法
fread(void *buffer, size_t size, size_t count, FILE *file_stream);
参数
此功能将需要所有4个参数。让我们了解参数。
buffer-这是缓冲存储块的指针,其中存储从流读取的字节。
大小-它定义了每个要读取的元素的大小(以字节为单位)。(size_t是无符号整数)。
count-要读取的元素数。\
file_stream-我们要从中读取字节的文件流的指针。
返回值
返回成功读取的元素数。
如果发生任何读取错误或到达文件末尾,则返回的元素数将与count变量不同。
示例
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main() {
FILE* file_stream;
char buf[100];
file_stream = fopen("tp.txt", "r");
while (!feof(file_stream)) //will read the file {
//将读取文件的内容。
fread(buf, sizeof(buf), 1, file_stream);
cout << buf;
}
return 0;
}假设tp.txt文件具有以下内容
nhooo
贡献
这里有什么
输出结果
如果我们运行上面的代码,它将生成以下输出-
nhooo Contribution anything here
让我们以示例为例,并在计数为零且大小为零时检查输出。
示例
#include <iostream>
#include <cstdio>
using namespace std; int main() {
FILE *fp;
char buffer[100];
int retVal;
fp = fopen("tpempty.txt","rb");
retVal = fread(buffer,sizeof(buffer),0,fp);
cout << "The count = 0, then return value = " << retVal << endl;
retVal = fread(buffer,0,1,fp);
cout << "The size = 0, then value = " << retVal << endl;
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
The count = 0, then return value = 0 The size = 0, then value = 0