C language to read a file stream of related functions

  • 2020-04-02 03:19:00
  • OfStack

C fread() function: read file function (read data from file stream)

The header file:


#include <stdio.h>

Definition function:


size_t fread(void * ptr, size_t size, size_t nmemb, FILE * stream);

Fread () is used to read data from a file stream.

Parameters, the stream is already open file pointer PTR to deposit to read in the data space, read the character parameters of size * nmemb. Fread () will return the actual read nmemb number, if this value is small than nmemb parameters, represents may read to the end of the file or have errors occur, then must use feof () or ferror () to determine what happens.

Return value: returns the number of nmemb actually read.

sample


#include <stdio.h>
#define nmemb 3
struct test
{
  char name[20];
  int size;
} s[nmemb];

main()
{
  FILE * stream;
  int i;
  stream = fopen("/tmp/fwrite", "r");
  fread(s, sizeof(struct test), nmemb, stream);
  fclose(stream);
  for(i = 0; i < nmemb; i++)
    printf("name[%d]=%-20s:size[%d]=%dn", i, s[i].name, i, s[i].size);
}

perform


name[0]=Linux! size[0]=6
name[1]=FreeBSD! size[1]=8
name[2]=Windows2000 size[2]=11

C feof() function: checks if the file stream reads the end of the file
The header file:


#include <stdio.h>

Definition function:


int feof(FILE * stream);

Feof () is used to detect whether the end of a file has been read. The trailing stream is the pointer to the file returned by fopen().

Return value: returns a non-zero value to indicate that the end of the file has been reached.


Related articles: