⚙️ C++

使用字符串方法——C++ 完全指南:详细指南

Here is the translated HTML article in English, following all your rules.

What is it and why? (a real-life analogy)

Imagine you are writing an essay in a notebook. While you are writing, the information exists. But as soon as you close the notebook and put it in your backpack, does the information disappear from your head? No, it remains on the paper. Tomorrow you will open the notebook and be able to read it again. A computer program works the same way: while it is running, data lives in RAM (like in your head). But as soon as the program closes, everything is lost. To save information forever, you need to write it to a file — like in a notebook.

Working with files in C++ is the ability of your program to read data from files (for example, from a text document, an Excel spreadsheet, a game configuration file) and write data to them. Without this, any program is like a fish out of water: it exists, but cannot interact with the outside world.

Simple analogy: Imagine your program is a chef. RAM is the cutting board he works on. The file is the refrigerator where ingredients (data) are stored. The chef can take ingredients from the refrigerator (read a file), cook a dish, and put it back (write to a file). Without a refrigerator, the chef can only cook what is on the board, and everything will be lost when he leaves.

Why is this needed in real life?

  • Games: saving progress, loading levels, reading graphics settings.
  • Text editors: opening and saving documents.
  • Databases: reading and writing millions of records.
  • Configuration files: programs read settings from files (e.g., config.ini).
  • Logging: writing errors and events to a file for later analysis.

In this article, we will take a detailed look at how to read data from files in C++. You will learn how to open a file, read a line, a number, an entire text from it, and how to avoid common mistakes.

Theory: how it works internally

To understand how file reading works, you need to look "under the hood" of the operating system and the C++ language.

Streams — the main concept

In C++, working with files is built on the concept of streams. A stream is an abstract concept that represents a sequence of bytes flowing from a source to a receiver. Imagine a water pipe: water flows through the pipe from the tap to the glass. Data "flows" from the file into your program (or vice versa) in the same way.

When you read a file, you create an input stream — data flows from the file into the program. When you write, you create an output stream.

Buffering — the secret to speed

Reading from a hard drive is a very slow operation (compared to the processor's work). If the program read every single byte individually, it would work hundreds of times slower. Therefore, C++ uses buffering.

Imagine you are drinking juice through a straw from a glass. You don't take one micro-sip at a time — you draw in a lot of liquid at once. A buffer is like that "glass" in the program's memory. When you ask to read 1 character, C++ actually reads a large chunk from the file (e.g., 4096 bytes) into the buffer all at once, and then gives you one character at a time from this buffer. When the buffer runs out, the next chunk is read. This is hundreds of times faster.

File opening modes

When you open a file, you must tell the system what you intend to do with it. This is called the opening mode. The main modes are:

Mode Flag Description
Read only ios::in The file is opened for reading only. If the file doesn't exist — an error.
Write only ios::out The file is opened for writing. If the file exists, it is cleared. If not, it is created.
Append to end ios::app Writing occurs at the end of the file. Existing data is not deleted.
Binary mode ios::binary The file is read as a stream of bytes, without character conversion (e.g., for images).

Modes can be combined using the | symbol (bitwise OR). For example: ios::in | ios::binary — open for reading in binary mode.

Classes for working with files

In C++, there are three main classes for working with files (all located in the header file <fstream>):

  • ifstream (input file stream) — for reading from a file.
  • ofstream (output file stream) — for writing to a file.
  • fstream (file stream) — universal, for reading and writing.

In this article, we will focus on ifstream, since the topic is reading files.

Syntax in C++: all forms and variants

Now let's move on to practice. How exactly do you write code to read a file? There are several ways, and we will cover each one.

1. Including the library

First of all, you need to include the header file <fstream>:

#include <fstream>  // Include the library for working with files
#include <iostream> // For output to the screen (cout)
#include <string>   // For working with strings
using namespace std; // So we don't have to write std:: before every word

2. Creating an object and opening a file

There are two ways to open a file:

Method 1: via the constructor


                                    
                ← 上一课
                C++ 中的错误处理与异常:详细指南
            
            
                                    
                下一步 →
                字符串方法 — C++ 完全指南:详细教程