> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/all-about-c++/file-handling.md).

# File Handling

**What Are File Streams?**

* **`std::ifstream`**: Used to read from files (input file stream).
* **`std::ofstream`**: Used to write to files (output file stream).

#### **Step-by-Step File Operations**

**A. Include Headers**

```cpp
#include <fstream>  // For file handling
#include <string>   // For std::string
```

**B. Reading a File (`std::ifstream`)**

```cpp
std::ifstream inputFile("data.txt");  // Open file

// Check if file opened successfully
if (!inputFile.is_open()) {
    std::cerr << "Error: Failed to open file!" << std::endl;
    return 1; // Exit with error code
}

// Read file line-by-line
std::string line;
while (std::getline(inputFile, line)) {
    std::cout << line << std::endl;
}

inputFile.close();  // Always close the file
```

**C. Writing to a File (`std::ofstream`)**

```cpp
std::ofstream outputFile("output.txt"); // Create/open file (overwrites by default)

if (!outputFile) { // Short error check
    std::cerr << "Error creating file!" << std::endl;
    return 1;
}

outputFile << "Hello, World!" << std::endl; // Write data
outputFile.close();
```

**D. File Opening Modes**

```cpp
// Append to existing file instead of overwriting
std::ofstream logFile("log.txt", std::ios::app);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/all-about-c++/file-handling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
