What is the role of the fopen()
function in C?
a) To open a file for reading or writing
b) To close a file
c) To write data to a file
d) To delete a file
Answer:
a) To open a file for reading or writing
Explanation:
The fopen()
function in C is used to open a file for reading, writing, or both. It returns a pointer to a FILE
object, which is then used by other file handling functions like fread()
, fwrite()
, and fclose()
. The fopen()
function requires two arguments: the name of the file and the mode (e.g., “r” for reading, “w” for writing, “a” for appending).
If the file cannot be opened, fopen()
returns NULL
, indicating that the file operation failed. Proper handling of this return value is essential to avoid errors and ensure that the program can handle file-related issues gracefully.