Unbuffered I/O in C, often associated with UNIX-like file routines, refers to direct communication with the underlying file system without using any intermediate buffering. This can lead to more immediate read and write operations but can also be less efficient for certain tasks compared to buffered I/O.
The UNIX-like file routines for unbuffered I/O include open, read, write, lseek, and close.
Opens a file and returns a file descriptor, which is an integer representing the open file.
#include <fcntl.h>
#include <unistd.h>
int fd = open("filename.txt", O_RDONLY); // Open for reading
if (fd == -1) {
// Handle error
}
Common flags for open:
O_RDONLY: Open for readingO_WRONLY: Open for writingO_RDWR: Open for reading and writingO_CREAT: Create the file if it does not existO_TRUNC: Truncate the file to zero lengthO_APPEND: Append to the fileReads data from an open file into a buffer.
ssize_t bytesRead;
char buffer[100];
bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead == -1) {
// Handle error
}
Writes data from a buffer to an open file.
ssize_t bytesWritten;
const char *data = "Hello, World!";
bytesWritten = write(fd, data, strlen(data));
if (bytesWritten == -1) {
// Handle error
}
Moves the file pointer to a specified location in the file.
off_t newPos = lseek(fd, offset, SEEK_SET); // Move to 'offset' from the beginning
if (newPos == (off_t)-1) {
// Handle error
}
Seek constants:
SEEK_SET: From the beginning of the fileSEEK_CUR: From the current positionSEEK_END: From the end of the fileCloses an open file descriptor.
if (close(fd) == -1) {
// Handle error
}
Here is a complete example demonstrating unbuffered I/O operations:
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main() {
int fd;
ssize_t bytesRead, bytesWritten;
char buffer[100];
// Open a file for writing (create if it doesn't exist)
fd = open("unbuffered.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("Error opening file for writing");
return 1;
}
// Write data to the file
const char *data = "Unbuffered I/O example.\n";
bytesWritten = write(fd, data, strlen(data));
if (bytesWritten == -1) {
perror("Error writing to file");
close(fd);
return 1;
}
// Close the file
if (close(fd) == -1) {
perror("Error closing file");
return 1;
}
// Open the file for reading
fd = open("unbuffered.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
return 1;
}
// Read data from the file
bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
perror("Error reading from file");
close(fd);
return 1;
}
// Null-terminate the buffer and print it
buffer[bytesRead] = '\0';
printf("Read from file:\n%s", buffer);
// Close the file
if (close(fd) == -1) {
perror("Error closing file");
return 1;
}
return 0;
}