What is fopen_s in C?

The fopen_s function in C is used to securely open files in different modes such as reading and writing. It is secure as it performs robust security checks on the arguments passed to it. For example, it would return an error if the pointer passed to it was NULL. Similarly, it requires the file access mode to be specified in its arguments to set the appropriate permission based on user type.

The fopen_s function is only available since the C11 standard. Otherwise, we can not use the function. So make sure that you have C11 enabled on your system!

The following must be defined before including the<stdio.h> library to use fopen_s:

#define __STDC_WANT_LIB_EXT1__ 1

Syntax

errno_t fopen_s(FILE** pFile, const char *filename, const char *mode);

Parameters

The fopen_s functions takes in three arguments:

  • pFile – Points to the file pointer that points to the opened file
  • filename – Denotes name of the file that will be opened
  • mode – Access mode in which the file is opened

Access Modes

Mode Details
r Only allows to read the contents of an existing file.
w Allows the user to write to a new file. If the file already exists, its contents are erased.
a Writes or appends at the end of an existing file without removing the EOF marker. In case the file does not exist, it is created.
r+ Allows for both reading and writing to an existing file only.
w+ Allows for both reading and writing to a new file. If the file exists, its contents are erased.
a+ Allows for reading and appending to the end an existing file. Note that the EOF marker will be removed. If the file does not exist, it is created.

Return Value

fopen_s returns 0 if executed successfully. Otherwise, it returns the error code.

Example

The following code snippet shows how to use fopen_s in C. It opens a single file in two different modes and informs the user in case the function could not execute successfully. If the error code is not 0, the program prints a statement to indicate the error, as seen here:

#define __STDC_WANT_LIB_EXT1__ 1
#define _GNU_SOURCE
#include <stdio.h>
FILE *file1, *file2;
int main()
{
//Declaring a variable of type errno_t to store the return value of fopen_s
errno_t error_code;
//Opening file in r mode
error_code = fopen_s(&file1, "myfile.c", "r");
if (error_code != 0){
printf("Error! Failed to open file in r mode!";
}
else{
printf( "I opened myfile.c in r mode!\n");
}
//Opening file in w+ mode
error_code = fopen_s(&file2, "myfile.c", "w+");
if (error_code != 0){
printf("Error! Failed to open file in w+ mode!";
}
else{
printf("Now I have opened myfile.c in write+ mode!");
printf("Oops! I just realised it contents got erased!");
}
//Closing all files
fcloseall();
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved