0% found this document useful (0 votes)
0 views

File Basic

These comprehensive notes cover essential aspects of C++ file handling, including file operations, stream classes, file modes, and error handling. The document provides practical examples and common exam problems to aid in exam preparation. Key topics include the differences between text and binary files, file pointers, and various coding challenges related to file handling.

Uploaded by

shreyas kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

File Basic

These comprehensive notes cover essential aspects of C++ file handling, including file operations, stream classes, file modes, and error handling. The document provides practical examples and common exam problems to aid in exam preparation. Key topics include the differences between text and binary files, file pointers, and various coding challenges related to file handling.

Uploaded by

shreyas kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

# Comprehensive C++ File Handling Notes for Exam Preparation

## Table of Contents
1. [Introduction to File Handling](#introduction-to-file-handling)
2. [Streams in C++](#streams-in-c++)
3. [File Operations](#file-operations)
4. [File Opening Modes](#file-opening-modes)
5. [Text vs Binary Files](#text-vs-binary-files)
6. [File Pointers and Random Access](#file-pointers-and-random-access)
7. [Error Handling](#error-handling)
8. [Practical Examples](#practical-examples)
9. [Common Exam Problems](#common-exam-problems)

---

## Introduction to File Handling

### Why Use Files?


- **Permanent Storage**: Data remains even after program termination
- **Large Data Handling**: Files can store much more data than variables in memory
- **Data Sharing**: Multiple programs can access the same file
- **Efficiency**: Avoids repeatedly entering the same data

### File Handling Basics


- Files are stored on secondary storage devices (hard disks, SSDs)
- C++ treats files as streams of bytes
- Two main types: text files and binary files

### File I/O Steps


1. Include `<fstream>` header
2. Declare file stream objects
3. Open the file (associate with physical file)
4. Perform read/write operations
5. Close the file

---

## Streams in C++

### What is a Stream?


A stream is a sequence of bytes flowing from source to destination. In C++, streams are
represented as objects of specific classes.

### Stream Classes Hierarchy


```
ios (Base class)
├── istream (Input stream)
│ ├── ifstream (Input file stream)
│ └── istream_withassign (e.g., cin)
└── ostream (Output stream)
​ ├── ofstream (Output file stream)
​ └── ostream_withassign (e.g., cout, cerr, clog)
```

### Important Stream Classes


1. **ifstream**: For reading from files
2. **ofstream**: For writing to files
3. **fstream**: For both reading and writing

### Predefined Stream Objects


- `cin`: Standard input (keyboard)
- `cout`: Standard output (screen)
- `cerr`: Unbuffered error output
- `clog`: Buffered error output

---

## File Operations

### Opening Files


Two ways to open files:

1. **Using Constructor**
```cpp
ofstream outFile("data.txt"); // opens for writing
ifstream inFile("data.txt"); // opens for reading
```

2. **Using open() function**


```cpp
fstream file;
file.open("data.txt", ios::out); // opens for writing
```

### Checking File Open Status


```cpp
if (!file) {
​ cout << "Error opening file!";
​ return 1;
}
// OR
if (!file.is_open()) {
​ cout << "File not opened!";
​ return 1;
}
```

### Closing Files


Always close files after operations:
```cpp
file.close();
```

### Basic File Operations


| Operation | Function | Example |
|-----------|----------|---------|
| Write | `<<` or `put()` | `file << "Hello";` or `file.put('A');` |
| Read | `>>` or `get()` | `file >> var;` or `ch = file.get();` |
| Read line | `getline()` | `getline(file, str);` |
| Binary write | `write()` | `file.write((char*)&obj, sizeof(obj));` |
| Binary read | `read()` | `file.read((char*)&obj, sizeof(obj));` |

---

## File Opening Modes

| Mode | Description |
|------|-------------|
| `ios::in` | Open for reading (default for ifstream) |
| `ios::out` | Open for writing (default for ofstream) |
| `ios::app` | Append to end of file |
| `ios::ate` | Open and seek to end |
| `ios::trunc` | Truncate file if exists |
| `ios::binary` | Open in binary mode |
| `ios::nocreate` | Open fails if file doesn't exist |
| `ios::noreplace` | Open fails if file exists |

**Combining modes**:
```cpp
file.open("data.txt", ios::out | ios::app | ios::binary);
```

---

## Text vs Binary Files

### Text Files


- Human-readable format
- Stores data as ASCII characters
- Uses `<<` and `>>` operators
- Newline characters are translated (platform-dependent)
### Binary Files
- Stores exact memory representation
- More efficient for large data
- Uses `read()` and `write()` functions
- No character translation occurs

### Comparison
| Aspect | Text File | Binary File |
|--------|-----------|-------------|
| Format | Human-readable | Machine-readable |
| Size | Larger (stores as text) | Smaller (stores raw data) |
| Portability | More portable | May have platform issues |
| Access | Sequential | Random access possible |
| Functions | `<<`, `>>`, `get()`, `put()` | `read()`, `write()` |

---

## File Pointers and Random Access

### File Pointers


Each file has two pointers:
1. **Get pointer**: Current read position (ifstream)
2. **Put pointer**: Current write position (ofstream)

### Pointer Manipulation Functions


| Function | Description |
|----------|-------------|
| `tellg()` | Returns current get pointer position |
| `tellp()` | Returns current put pointer position |
| `seekg(pos)` | Moves get pointer to absolute position |
| `seekp(pos)` | Moves put pointer to absolute position |
| `seekg(offset, dir)` | Moves get pointer relative to dir |
| `seekp(offset, dir)` | Moves put pointer relative to dir |

### Reference Positions


- `ios::beg`: Beginning of file
- `ios::cur`: Current position
- `ios::end`: End of file

**Examples**:
```cpp
file.seekg(10); // Move to 10th byte from start
file.seekg(-5, ios::cur); // Move back 5 bytes
file.seekg(0, ios::end); // Move to end
```

---
## Error Handling

### Error Status Flags


| Flag | Meaning |
|------|---------|
| `goodbit` | No errors |
| `eofbit` | End of file reached |
| `failbit` | Logical error (e.g., wrong type) |
| `badbit` | Read/write error |
| `hardfail` | Fatal error |

### Error Checking Functions


| Function | Returns true when |
|----------|-------------------|
| `good()` | No errors |
| `eof()` | End of file reached |
| `fail()` | `failbit` or `badbit` set |
| `bad()` | `badbit` set |
| `clear()` | Clears error flags |

**Example**:
```cpp
while (file.good()) {
​ // Read file
}
if (file.eof()) {
​ cout << "End of file reached";
}
```

---

## Practical Examples

### 1. Writing to Text File


```cpp
#include <fstream>
using namespace std;

int main() {
​ ofstream out("data.txt");
​ if (!out) {
​ cout << "Error opening file";
​ return 1;
​ }

​ out << "Hello World\n";


​ out << 42 << endl;
​ out.close();
​ return 0;
}
```

### 2. Reading from Text File


```cpp
#include <fstream>
#include <iostream>
using namespace std;

int main() {
​ ifstream in("data.txt");
​ if (!in) {
​ cout << "Error opening file";
​ return 1;
​ }

​ string line;
​ while (getline(in, line)) {
​ cout << line << endl;
​ }
​ in.close();
​ return 0;
}
```

### 3. Binary File Operations


```cpp
struct Person {
​ char name[50];
​ int age;
};

// Writing
Person p = {"John", 25};
ofstream out("person.dat", ios::binary);
out.write((char*)&p, sizeof(p));
out.close();

// Reading
Person p2;
ifstream in("person.dat", ios::binary);
in.read((char*)&p2, sizeof(p2));
cout << p2.name << " " << p2.age;
in.close();
```
---

## Common Exam Problems

### Theory Questions


1. Explain the difference between text and binary files.
2. What are file modes in C++? Explain each.
3. Describe the stream class hierarchy in C++.
4. What are file pointers? How are they manipulated?
5. Explain error handling in file operations.

### Coding Problems


1. Write a program to copy contents of one file to another.
2. Create a program to search for a record in a binary file.
3. Implement a program to append data to an existing file.
4. Write a program that displays a file in reverse order.
5. Create a student record system using file handling.

### Sample Solution (Student Record System)


```cpp
#include <iostream>
#include <fstream>
using namespace std;

class Student {
​ int roll;
​ char name[30];
​ float marks;
public:
​ void getData() {
​ cout << "Enter roll, name, marks: ";
​ cin >> roll >> name >> marks;
​ }
​ void display() {
​ cout << roll << "\t" << name << "\t" << marks << endl;
​ }
​ int getRoll() { return roll; }
};

int main() {
​ fstream file("students.dat", ios::binary | ios::in | ios::out | ios::app);
​ Student s;
​ char ch;

​ do {
​ s.getData();
​ file.write((char*)&s, sizeof(s));
​ cout << "Add more? (y/n): ";
​ cin >> ch;
​ } while (ch == 'y' || ch == 'Y');

​ file.seekg(0); // Rewind to start

​ cout << "\nStudent Records:\n";


​ while (file.read((char*)&s, sizeof(s))) {
​ s.display();
​ }

​ file.close();
​ return 0;
}
```

---

These comprehensive notes cover all essential aspects of C++ file handling for your exam
preparation, combining theoretical concepts with practical examples and common exam
problems.

You might also like