如何使用fread()

text
阅读 60 收藏 0 点赞 0 评论 0

fread_c.txt
So with fgetc() we only read one char from the file and store it. What if we want to be able to read and store a chunk of data from the file and store it? So we will need to use fread().

fread():

fread(<buffer>, <size>, <qty>, <file pointer>);

Reads <qty> units of size <size> from the file pointed to and stores them in memory in a buffer (usually an array) pointed to by <buffer>.

* Also note that the file pointer should only be opened as "r", or else will suffer an error.

Example:

int arr[10];
fread(arr, sizeof(int), 10, ptr);

So first we create a buffer, that is a chunk of memory, using an array. So we set memory space for 10 integers.

So then we read 10 integers from "ptr" and store them into the array "arr". Because the array name is it's address, that's why we just type "arr" in the first parameter.

So the first parameter in "fread()" is the memory address for the buffer. So it's a pointer variable. If the buffer is an array, just use the array's name. If it's a variable, we need to get the memory address of that variable:

char c;
fread(&c, sizeof(char), 1, ptr);

So here for variable "c", we need to get it's address to put in the first parameter of fread() to point to where the buffer is.

** be aware that the last parameter is file pointer, not file name.

We can also dynamically allocate memory and use fread():

double* arr2 = malloc(sizeof(double) * 80);
fread(arr2, sizeof(double), 80, ptr);

So here we dynamically allocate memory space using "malloc()". Here we allocated memory space for 80 doubles. 
评论列表


问题


面经


文章

微信
公众号

扫码关注公众号