Simple question,
When i use fread:
fread(ArrayA, sizeof(Reg), sizeBlock, fp);
My file pointer, fp
is moved ahead?
Simple question,
When i use fread:
fread(ArrayA, sizeof(Reg), sizeBlock, fp);
My file pointer, fp
is moved ahead?
Answer: Yes, the position of the file pointer is updated automatically after the read operation, so that successive fread()
functions read successive file records.
Clarification: fread()
is a block oriented function. The standard prototype is:
size_t fread(void *ptr,
size_t size,
size_t limit,
FILE *stream);
The function reads from the stream pointed to by stream
and places the bytes read into the array pointed to by ptr
, It will stop reading when any of the following conditions are true:
limit
elements of size size
, or fread()
gives you as much control as fgetc()
, and has the advantage of being able to read more than one character in a single I/O operation. In fact, memory permitting, you can read the entire file into an array and do all of your processing in memory. This has significant performance advantages.
fread()
is often used to read fixed-length data records directly into structs, but you can use it to read any file. It's my personal choice for reading most disk files.
Yes, calling fread does indeed move the file pointer. The file pointer will be advanced by the number of bytes actually read. In case of an error in fread, the file position after calling fread is unspecified.
Yes, The fp
will be advanced by the total amount of bytes read.
In your case the function fread reads sizeBlock
objects, each sizeof(Reg)
bytes long, from the stream pointed to by fp
, storing them at the location given by ArrayA
.
Yes, it does. It could be checked by using ftell() function in order to show current position (in fact, bytes read so far), take a look it:
int main() {
typedef struct person {
char *nome; int age;
} person;
// write struct to file 2x or more...
FILE *file = fopen(filename, "rb");
person p;
size_t byteslength = sizeof(struct person);
printf("ftell: %ld\n", ftell(file));
fread(&p, byteslength, 1, file);
printf("name: %s | age: %d\n", p.nome, p.idade);
printf("ftell: %ld\n", ftell(file));
fread(&p, byteslength, 1, file);
printf("name: %s | age: %d\n", p.nome, p.idade);
//...
fclose(file);
return 0;
}
© 2022 - 2024 — McMap. All rights reserved.