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()



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M