Practical IO Techniques
File Handling Strategies
graph TD
A[File IO Techniques] --> B[Sequential Read/Write]
A --> C[Random Access]
A --> D[Memory Mapped IO]
A --> E[Buffered IO]
Sequential File Reading
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
char buffer[256];
// Read line by line
while (fgets(buffer, sizeof(buffer), file)) {
printf("Read: %s", buffer);
}
fclose(file);
return 0;
}
Advanced IO Techniques
Memory Mapped IO
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("largefile.dat", O_RDWR);
// Memory map entire file
char *mapped = mmap(NULL, file_size,
PROT_READ|PROT_WRITE,
MAP_SHARED, fd, 0);
// Direct memory access
mapped[0] = 'A';
munmap(mapped, file_size);
close(fd);
return 0;
}
IO Method |
Speed |
Use Case |
Buffered IO |
Medium |
Standard Files |
Direct IO |
High |
Large Files |
Memory Mapped |
Fastest |
Frequent Access |
Non-Blocking IO
#include <fcntl.h>
#include <errno.h>
int main() {
int fd = open("device.txt", O_RDONLY | O_NONBLOCK);
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1 && errno == EAGAIN) {
// Resource temporarily unavailable
printf("LabEx: Non-blocking read\n");
}
close(fd);
return 0;
}
Asynchronous IO Techniques
Using Select Mechanism
#include <sys/select.h>
int main() {
fd_set read_fds;
struct timeval timeout;
FD_ZERO(&read_fds);
FD_SET(STDIN_FILENO, &read_fds);
timeout.tv_sec = 5;
timeout.tv_usec = 0;
int ready = select(STDIN_FILENO + 1,
&read_fds, NULL, NULL, &timeout);
return 0;
}
Stream Optimization Strategies
- Use appropriate buffer sizes
- Minimize system calls
- Leverage memory mapping for large files
- Implement non-blocking IO for responsive applications
Error Handling Best Practices
#include <stdio.h>
#include <errno.h>
void safe_file_operation() {
FILE *file = fopen("data.txt", "r");
if (!file) {
fprintf(stderr, "Error: %s\n", strerror(errno));
return;
}
// File operations
if (ferror(file)) {
// Handle IO errors
}
fclose(file);
}
Key Takeaways
- Choose IO technique based on specific requirements
- Understand trade-offs between different IO methods
- Implement robust error handling
- Optimize for performance in LabEx environments
By mastering these practical IO techniques, developers can create efficient, responsive, and robust Linux applications with advanced input/output capabilities.