简体   繁体   中英

Using the function fread() to read blocks of data in a file

If I use

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream ),

how can I derefence the data pointed by ptr?. Like if I have

int main()
{
void *ptr
fread(ptr,1,100,file);
printf("%s",ptr);
}

You misunderstand the purpose of void * ptr in the declaration of fread .

From http://en.cppreference.com/w/c/io/fread

buffer - pointer to the array where the read objects are stored

First, the argument must be a valid pointer where objects can be stored. Using

void *ptr;
fread(ptr,1,100,file);

will lead to undefined behavior since ptr does not point to anything valid.

Second, the reason for the argument type is void* to allow you to read all kinds of data from a stream. Eg

// Read an integer
int i;
fread(&i, sizeof(int), 1, file);

// Read 10 integers
int a[10];
fread(a, sizeof(int), 10, file);

// Read a double
double d;
fread(&d, sizeof(double), 1, file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM