What are the functions to open and close the file in C language?

The fopen() function is used to open file whereas fclose() is used to close file.

In C language, to open and close files, you typically use the functions fopen() and fclose() respectively.

  1. fopen(): This function is used to open a file. It takes two arguments: the name of the file to be opened and the mode in which you want to open the file (read, write, append, etc.). It returns a FILE pointer which is used to access the file.
    c
    FILE *fptr;
    fptr = fopen("filename.txt", "r"); // opens a file named filename.txt in read mode
  2. fclose(): This function is used to close an open file. It takes a FILE pointer as its argument, which is the same pointer returned by fopen().
    c
    fclose(fptr); // closes the file associated with the FILE pointer fptr

It’s important to check the return values of these functions to handle errors properly, especially when opening files, as they may fail due to various reasons like the file not existing, insufficient permissions, etc.