C ++中的fread()函数
C/C++库函数size_tfread(void*ptr,size_tsize,size_tnmemb,FILE*stream)将数据从给定流读取到ptr指向的数组中。以下是fread()函数的声明。
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
下表包含fread()参数和说明:
成功读取的元素总数作为size_t对象返回,该对象是整数数据类型。如果此数字与nmemb参数不同,则说明发生错误或到达文件末尾。
范例程式码
#include <stdio.h>
#include <string.h>
int main () {
FILE *fp;
char c[] = "this is nhooo";
char buffer[100];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
return(0);
}让我们编译并运行以上程序,该程序将创建文件file.txt并编写一个内容为nhooo的内容。之后,我们使用fseek()函数将写入指针重置为文件的开头,并准备文件内容,如下所示-
输出结果
this is nhooo