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



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

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