Skip to content

[Feature]: Add C++ Language Course #3800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions courses/C++ /advance-Level/Advance-File-Handling/File-locking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
---
id: lesson-1
title: "Advanced File Handling in C++"
sidebar_label: Advanced File Handling
sidebar_position: 1
description: "Learn Advanced File Handling in C++"
tags: [courses,Advance-level,Introduction]
---


Advanced file handling techniques allow for better control, performance optimization, and handling of large files. Let's explore these techniques:

### Flowchart

```mermaid
graph TD;
A[Start] --> B[File Locking Mechanisms];
B --> C[File I/O Performance Optimization];
C --> D[Handling Large Files];
D --> E[Working with Memory-Mapped Files];
E --> F[End];
```

#### 1. File Locking Mechanisms

File locking prevents simultaneous access to a file, which can cause data corruption. It ensures that only one process can write to a file at a time.

##### Example: File Locking with `fcntl`

```cpp
#include <iostream>
#include <fcntl.h>
#include <unistd.h>

int main() {
int fd = open("example.txt", O_RDWR | O_CREAT, 0666);
if (fd == -1) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}

struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // Lock the whole file

if (fcntl(fd, F_SETLK, &lock) == -1) {
std::cerr << "Failed to lock file" << std::endl;
close(fd);
return 1;
}

std::cout << "File locked. Press Enter to unlock..." << std::endl;
std::cin.get();

lock.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &lock) == -1) {
std::cerr << "Failed to unlock file" << std::endl;
}

close(fd);
return 0;
}
```

#### 2. File I/O Performance Optimization

Optimizing file I/O can significantly improve performance, especially when dealing with large files or high-frequency I/O operations.

:::tip
- **Buffering**: Use buffered I/O for efficient data handling.
- **Asynchronous I/O**: Perform non-blocking I/O operations to avoid waiting for I/O completion.
- **Memory Mapping**: Use memory-mapped files for direct memory access to file contents.
:::

#### 3. Handling Large Files

Handling large files efficiently is crucial for applications that deal with massive datasets.

##### Example: Reading Large Files in Chunks

```cpp
#include <iostream>
#include <fstream>

int main() {
std::ifstream file("largefile.txt", std::ios::in | std::ios::binary);
if (!file) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}

const size_t bufferSize = 1024 * 1024; // 1 MB buffer
char buffer[bufferSize];

while (file.read(buffer, bufferSize) || file.gcount() > 0) {
// Process buffer contents
std::cout.write(buffer, file.gcount());
}

file.close();
return 0;
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Advance File Handling",
"position": 5,
"link": {
"type": "generated-index",
"description": "Learn Advance File Handling."
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
id: lesson-2
title: "Working with Memory-Mapped Files"
sidebar_label: Working with Memory-Mapped Files
sidebar_position: 2
description: "Learn Working with Memory-Mapped Files"
tags: [courses,Advance-level,Introduction]
---


Memory-mapped files allow for efficient file access by mapping a file's contents to memory. This technique is useful for large files and random access patterns.

##### Example: Memory-Mapped File Access

```cpp
#include <iostream>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
int fd = open("largefile.txt", O_RDONLY);
if (fd == -1) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}

struct stat sb;
if (fstat(fd, &sb) == -1) {
std::cerr << "Failed to get file size" << std::endl;
close(fd);
return 1;
}

size_t fileSize = sb.st_size;
char *mapped = static_cast<char *>(mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE, fd, 0));
if (mapped == MAP_FAILED) {
std::cerr << "Failed to map file" << std::endl;
close(fd);
return 1;
}

// Access the file content through the mapped memory
std::cout.write(mapped, fileSize);

if (munmap(mapped, fileSize) == -1) {
std::cerr << "Failed to unmap file" << std::endl;
}

close(fd);
return 0;
}
```
:::tip
- **File Locking**: Use file locking mechanisms to prevent concurrent write operations.
- **Buffered I/O**: Implement buffering to reduce the number of I/O operations.
- **Asynchronous I/O**: Utilize asynchronous I/O for non-blocking operations.
- **Memory Mapping**: Use memory-mapped files for efficient access to large files.
:::


Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Advanced Memory Allocation",
"position": 2,
"link": {
"type": "generated-index",
"description": "Learn Advanced Memory Allocation."
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
---
id: lesson-2
title: "Custom Allocators"
sidebar_label: Custom Allocators
sidebar_position: 2
description: "Learn Custom Allocators"
tags: [courses,Advance-level,Introduction]
---

**Custom Allocators**: Custom allocators provide control over memory allocation strategies and can be used to optimize memory usage for specific applications.

##### Example: Custom Allocator

```cpp
#include <iostream>
#include <memory>
#include <vector>

template<typename T>
class CustomAllocator : public std::allocator<T> {
public:
typedef T value_type;

T* allocate(std::size_t n) {
std::cout << "Allocating " << n << " elements." << std::endl;
return std::allocator<T>::allocate(n);
}

void deallocate(T* p, std::size_t n) {
std::cout << "Deallocating " << n << " elements." << std::endl;
std::allocator<T>::deallocate(p, n);
}
};

int main() {
std::vector<int, CustomAllocator<int>> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);

std::cout << "Vector size: " << vec.size() << std::endl;
return 0;
}
```

**Output:**
```
Allocating 1 elements.
Allocating 1 elements.
Allocating 1 elements.
Vector size: 3
Deallocating 1 elements.
Deallocating 1 elements.
Deallocating 1 elements.
```

### Memory Alignment and Padding

**Memory Alignment and Padding**: Memory alignment refers to arranging data in memory to meet certain hardware requirements. Padding is used to align data structures in memory.

##### Example: Memory Alignment

```cpp
#include <iostream>
#include <cstddef> // For offsetof

struct AlignedStruct {
char a;
int b;
double c;
};

int main() {
std::cout << "Size of AlignedStruct: " << sizeof(AlignedStruct) << std::endl;
std::cout << "Offset of 'a': " << offsetof(AlignedStruct, a) << std::endl;
std::cout << "Offset of 'b': " << offsetof(AlignedStruct, b) << std::endl;
std::cout << "Offset of 'c': " << offsetof(AlignedStruct, c) << std::endl;

return 0;
}
```

**Output:**
```
Size of AlignedStruct: 16
Offset of 'a': 0
Offset of 'b': 4
Offset of 'c': 8
```



:::tip
- **Memory Pools**: Useful for scenarios with frequent allocation and deallocation. They reduce fragmentation and improve performance.
- **Smart Pointers**: Prefer using `unique_ptr` for single ownership, `shared_ptr` for shared ownership, and `weak_ptr` for non-owning references.
- **Custom Allocators**: Utilize custom allocators for specialized memory management needs, especially in performance-critical applications.
- **Memory Alignment**: Ensure data structures are aligned properly to meet hardware requirements and avoid performance penalties.
:::
Loading
Loading