搜尋此網誌

2026年1月16日星期五

Working with files

In C++, the fstream class (from the header) is used for both reading and writing files. It combines the functionality of ifstream (input file stream) and ofstream (output file stream), allowing you to open a file and perform input/output operations on it.

The is_open() function in C++ is a member of the file stream classes (ifstream, ofstream, and fstream). It is used to check whether a file stream is currently associated with (and successfully opened) a file.

getline() in C++ — it’s one of the most useful functions for reading text input, especially when dealing with files or user input that includes spaces.

#include <iostream>

#include <string>

using namespace std;


int main() {

    string name;

    cout << "Enter your full name: ";

    getline(cin, name);  // reads entire line including spaces

    cout << "Hello, " << name << "!" << endl;

    return 0;

}


ios::app is a file open mode flag used with file streams (ofstream, fstream).

Meaning: Append mode.

When you open a file with ios::app, all output operations are performed at the end of the file, preserving existing content.

The file pointer is moved to the end before each write.

Existing data is not erased.


console: a flat surface that contains all the controls and switches for a machine, a piece of electronic equipment, etc.


ios::in

  • Meaning: Open file for input (reading).
  • Behavior:
    • The file must exist; otherwise, opening fails.
    • You can read data from the file using the stream.
  • Typical use: Used with ifstream or fstream.

ios::out

  • Meaning: Open file for output (writing).
  • Behavior:
    • If the file exists, its contents are truncated (erased) unless combined with ios::app.
    • If the file doesn’t exist, it is created.
    • You can write data into the file.
  • Typical use: Used with ofstream or fstream.


The .close() function in C++ is used with file stream objects (ifstream, ofstream, fstream) to close an open file.


Microsoft Copilot

沒有留言:

發佈留言