C++ 程序中的 fread() 函数
给定的任务是展示 fread() 在 C++ 中的工作原理。在本文中,我们还将了解传递给 fread() 的不同参数以及此函数返回的内容。
fread() 是 C++ 的一个内置函数,用于从流中读取数据块。此函数计算从流中读取的每个大小为“size”字节的对象的数量,并将它们存储在缓冲区内存中,然后将位置指针向前移动读取的总字节数。如果读取成功,读取的字节数将为 size * count。
语法
fread(void *buffer, size_t size, size_t count, FILE *file_stream);
参数
此函数需要所有 4 个参数。让我们了解这些参数。
buffer - 这是一个指向缓冲区内存块的指针,从流中读取的字节将存储在此处。
size - 它定义了要读取的每个元素的大小(以字节为单位)。(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 {
// will read the contents of the file.
fread(buf, sizeof(buf), 1, file_stream);
cout << buf;
}
return 0;
}假设 tp.txt 文件包含以下内容
tutorialspoint
Contribution
anything here
输出
如果我们运行上述代码,它将生成以下输出:
tutorialspoint Contribution anything here
让我们举个例子,检查当 count 为零且 size 为零时的输出。
示例
#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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP