w3resource

C fopen() function

C library function - fopen()

The fopen() function opens the file that is specified by filename. A mode parameter specifies the type of access to the file that is requested. The mode variable contains one positional parameter followed by optional keyword parameters.

Syntax:

FILE *fopen(const char *filename, const char *mode)

fopen() Parameters:

Name Description Required /Optional
filename File to be opened. Required
mode The mode argument points to a string. If the string is one of the following, the file shall be opened in the indicated mode. Otherwise, the behavior is undefined. Required

The possible values for the mode parameter:

Mode Description
r Open a text file for reading. The file must exist.
w Create a text file for writing. If the given file exists, its contents are destroyed unless it is a logical file.
a Open a text file in append mode for writing at the end of the file. The fopen() function creates the file if it does not exist and is not a logical file.
r+ Open a text file for both reading and writing. The file must exist.
w+ Create a text file for both reading and writing. If the given file exists, its contents are cleared unless it is a logical file.
a+ Open a text file in append mode for reading or updating at the end of the file. The fopen() function creates the file if it does not exist.
rb Open a binary file for reading. The file must exist.
wb Create an empty binary file for writing. If the file exists, its contents are cleared unless it is a logical file.
ab Open a binary file in append mode for writing at the end of the file. The fopen function creates the file if it does not exist.
r+b or rb+ Open a binary file for both reading and writing. The file must exist.
w+b or wb+ Create an empty binary file for both reading and writing. If the file exists, its contents will be cleared unless it is a logical file.
a+b or ab+ Open a binary file in append mode for writing at the end of the file. The fopen() function creates the file if it does not exist.

Return value from fopen()

  • Upon successful completion, fopen() shall return a pointer to the object controlling the stream. Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error.

Example: fopen() function

The following example attempts to open a file for reading.

#include <stdio.h>
#define  MAX_LEN  60
 
int main(void)
{
   FILE *stream;
   fpos_t position;
   char line1[MAX_LEN];
   char line2[MAX_LEN];
   char *result;
   char ch;
   int num;
 
   /* The following call opens a text file for reading.   */
   if ((stream = fopen("test.txt", "r")) == NULL)
      printf("Could not open data file\n");
   else if ((result = fgets(line1,MAX_LEN,stream)) != NULL)
           {
            printf("The string read from test.txt: %s\n", result);
            fclose(stream);
           }
 
   /* The following call opens a fixed record length file */
   /* for reading and writing.                            */
   if ((stream = fopen("test.txt", "rb+")) == NULL)
         printf("Could not open data file\n");
   else {
         fgetpos(stream, &position);
         if (!fread(line2,sizeof(line2),1,stream))
            perror("fread error");
         else printf("1st record read from test.txt: %s\n", line2);
 
         fsetpos(stream, &position);     /* Reset pointer to start of file */
         fputs(result, stream);     /* The line read from myfile is   */
                                    /* written to myfile2.            */
         fclose(stream);
        }
}

Output:

The string read from test.txt: Important information

fread error: No error

Error: The fopen() function shall fail if -

  • Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.
  • A signal was caught during fopen().
  • The named file is a directory and mode requires write access.
  • A loop exists in symbolic links encountered during resolution of the path argument.
  • All file descriptors available to the process are currently open.
  • The maximum allowable number of files is currently open in the system.
  • The directory or file system that would contain the new file cannot be expanded, the file does not exist, and the file was to be created.
  • The value of the mode argument is not valid.
  • The length of a component of a pathname is longer than {NAME_MAX}.
  • Insufficient storage space is available.
  • The file is a pure procedure (shared text) file that is being executed and mode requires write access.

C Programming Code Editor:

Previous C Programming: C fgetpos()
Next C Programming: C fread()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdio/c_library_method_fopen.php