Explain the freopen of function and fclose of function in C language

  • 2020-04-02 03:18:53
  • OfStack

C freopen() function: opens the file function and gets the file handle

The header file:


#include <stdio.h>

Definition function:


FILE * freopen(const char * path, const char * mode, FILE * stream);

Function description:
The path string contains the path and file name of the file to open.
Please refer to fopen() for parameter mode.
The parameter stream is a pointer to an open file. Freopen() closes the file stream opened by the original stream, and then opens the file with the parameter path.

Return value: after the file opens successfully, the file pointer to the stream is returned. If the file fails to open, NULL is returned and the error code is stored in errno.

sample


#include <stdio.h>
main()
{
  FILE * fp;
  fp = fopen("/etc/passwd", "r");
  fp = freopen("/etc/group", "r", fp);
  fclose(fp);
}

C fclose() function: close an open file
The header file:


#include <stdio.h>

Definition function:


int fclose(FILE * stream);

Function description: fclose() is used to close the file previously opened by fopen(). This action causes the data in the buffer to be written to the file and frees the file resources provided by the system.

Return value: returns 0 if the file action is successful, returns EOF if an error occurs and saves the error code to errno.

Error code: EBADF indicates that the parameter stream is not an open file.


Related articles: