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
errno_t fopen_s(FILE** pFile, const char *filename, const char *mode);
The fopen_s
functions takes in three arguments:
pFile
– Points to the file pointer that points to the opened filefilename
– Denotes name of the file that will be openedmode
– Access mode in which the file is openedMode | 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. |
fopen_s
returns 0 if executed successfully. Otherwise, it returns the error code.
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_serrno_t error_code;//Opening file in r modeerror_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+ modeerror_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 filesfcloseall();}
Free Resources