Vidyalelo
C++ Programming · Q16

File Handling in C++

Programming · C++ Programming · question 16

Q16

What is the function used to create a new file in C++?

A.
create()
B.
newFile()
C.
fopen()
D.
ofstream file()
Answer

Answer: Option D

Solution

Answer: Option D
Solution:
The correct answer is D: ofstream file()
Let's break down why:

Option A: create() - There isn't a standard C++ function called create() specifically for file creation.

Option B: newFile() - Similarly, newFile() is not a built-in C++ function for file handling.

Option C: fopen() - fopen() is a C function for file input/output, and while it *can* be used in C++, it's more common and idiomatic to use C++'s file stream classes.
fopen() also requires you to specify a mode (like "w" for write) which determines if you want to create the file, overwrite it, or append to it. It's generally less type-safe than C++ streams.

Option D: ofstream file() - This is the C++ way to create a new file. ofstream is a class from the C++ standard library designed for output file streams.
By creating an object of type ofstream (e.g., ofstream file;), you can automatically create a new file or open an existing one for writing (if the file doesn't exist, it will be created). You can then use the file object to write data to the file.
For Example : ofstream myFile("filename.txt"); will create a file named "filename.txt" or overwrite if it already exist .