File Handling

Cards (16)

  • What does C++ file handling refer to?
    Creating files and performing read/write operations
  • Which header file must be included for file handling in C++?
    #include <fstream>
  • What is the purpose of the ofstream class?
    To create or open and write to a file
  • What is the purpose of the ifstream class?
    To read a file
  • How do you create or open a text file in C++?
    Using ofstream writeFile("File1.txt");
  • What is the correct way to write to a file in C++?
    writeFile << "Text";
  • What does writeFile.close() do?
    It closes the file after writing
  • How can you check if a file is open in C++?
    Using writeFile.is_open()
  • What is the purpose of getline() in file reading?
    To read a line from the file
  • How do you display the content of a file in C++?
    Using cout << text;
  • What does the ios::out flag do?
    Creates or opens a file for writing
  • What does the ios::in flag do?
    Reads a file
  • What does the ios::app flag do?
    Appends new content to a file
  • What are the steps to create, write, and close a file in C++?
    1. Include necessary headers: <code>#include <iostream></code> and <code>#include <fstream></code>
    2. Create an ofstream object: <code>ofstream writeFile("File1.txt");</code>
    3. Write to the file: <code>writeFile << "Text";</code>
    4. Close the file: <code>writeFile.close();</code>
  • What are the steps to read and display the content of a file in C++?
    1. Include necessary headers: <code>#include <iostream></code> and <code>#include <fstream></code>
    2. Create an ifstream object: <code>ifstream readFile("File1.txt");</code>
    3. Check if the file is open: <code>if(readFile.is_open())</code>
    4. Use getline to read lines: <code>while (getline(readFile, text))</code>
    5. Display the content: <code>cout << text;</code>
    6. Close the file: <code>readFile.close();</code>
  • What is an alternative way to handle files using fstream?
    • Use <code>fstream</code> for both reading and writing
    • Flags:
    • <code>ios::out</code> for writing
    • <code>ios::in</code> for reading
    • <code>ios::app</code> for appending