Header file:
stdio.h
Synopsis:
size_t fread(void *ptr, size_t size_of_nobj, size_t nobj, FILE *stream);
Description:
Reads nobj of data, each of size sizeof_of_nobj from the stream and stores them in ptr. Returns number of objects read on success. Otherwise, feof or ferror is returned.
fread function C example:
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
int main() {
char *ptr, *str;
int nobj, ret, size;
FILE *fp;
fp = fopen("mastering-c.txt", "rb");
if (fp == NULL) {
str = strerror(errno);
perror(str);
return;
}
ret = fseek(fp, 0, SEEK_END);
if (ret != 0) {
str = strerror(errno);
perror(str);
return;
}
nobj = ftell(fp); // number of characters
size = sizeof(char);
rewind(fp);
ptr = (char *) malloc(sizeof(char) * size);
ret = fread(ptr, size, nobj, fp);
if (ret != nobj) {
str = strerror(errno);
perror(str);
return;
}
printf("ret: %d\tnobj: %d\nFile contents:\n%s", ret, nobj, ptr);
return 0;
}
#include<string.h>
#include<errno.h>
#include<stdlib.h>
int main() {
char *ptr, *str;
int nobj, ret, size;
FILE *fp;
fp = fopen("mastering-c.txt", "rb");
if (fp == NULL) {
str = strerror(errno);
perror(str);
return;
}
ret = fseek(fp, 0, SEEK_END);
if (ret != 0) {
str = strerror(errno);
perror(str);
return;
}
nobj = ftell(fp); // number of characters
size = sizeof(char);
rewind(fp);
ptr = (char *) malloc(sizeof(char) * size);
ret = fread(ptr, size, nobj, fp);
if (ret != nobj) {
str = strerror(errno);
perror(str);
return;
}
printf("ret: %d\tnobj: %d\nFile contents:\n%s", ret, nobj, ptr);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
ret: 75 nobj: 75
File contents:
Hello world
This is fread example program in C
Thanks for visiting our blog
jp@jp-VirtualBox:~/cpgms/exp$ cat mastering-c.txt
Hello world
This is fread example program in C
Thanks for visiting our blog
ret: 75 nobj: 75
File contents:
Hello world
This is fread example program in C
Thanks for visiting our blog
jp@jp-VirtualBox:~/cpgms/exp$ cat mastering-c.txt
Hello world
This is fread example program in C
Thanks for visiting our blog
No comments:
Post a Comment