File Handling Interview Questions

    Question 1C++ File Stream Declaration

    Which header file is required for file handling in C++?

    Question 2C++ File Modes

    Which mode is used to append data at the end of a file in C++?

    Question 3C++ Guess the Output – Writing File

    What will this program do?

    #include <iostream> #include <fstream> using namespace std; int main() { ofstream file("test.txt"); file << "Hello File"; file.close(); return 0; }

    Question 4C++ File Reading

    Which class is used to read from a file in C++?

    Question 5C++ Guess the Output – Reading File

    Suppose "data.txt" contains 1234. What will this program print?

    #include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); int x; file >> x; cout << x; file.close(); return 0; }

    Question 6C++ File Opening Multiple Modes

    Which of the following opens a file for both reading and writing?

    Question 7C++ Guess the Output – Appending File

    What will happen when this program runs?

    #include <iostream> #include <fstream> using namespace std; int main() { ofstream file("log.txt", ios::app); file << "New Entry\n"; file.close(); return 0; }

    Question 8C++ Binary File Mode

    Which flag is used to open a file in binary mode?

    Question 9C++ Guess the Output – getline from File

    Suppose "note.txt" contains:
    C++ is fun!
    What will this program print?

    #include <iostream> #include <fstream> using namespace std; int main() { ifstream file("note.txt"); string line; getline(file, line); cout << line; return 0; }

    Question 10C++ Closing File

    Why is file.close() used in C++?