README and fd: start a note to tell what I'm doing here ...

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2025-02-10 13:22:03 -05:00
parent d3a10d7190
commit f332b0868a
Signed by: vbatts
GPG key ID: E30EFAA812C6E5ED
2 changed files with 62 additions and 0 deletions

52
fd.cpp Normal file
View file

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
// Open a file for reading and writing
int fd = open("example.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
// int fd = 2; // jam in STDERR_FILENO ...
if (fd == -1) {
perror("Error opening file");
return EXIT_FAILURE;
}
// Write to the file
const char *text = "Hello, file descriptors!";
ssize_t bytes_written = write(fd, text, strlen(text));
if (bytes_written == -1) {
perror("Error writing to file");
close(fd);
return EXIT_FAILURE;
}
// Move the file offset to the beginning
if (lseek(fd, 0, SEEK_SET) == -1) {
perror("Error seeking in file");
close(fd);
return EXIT_FAILURE;
}
// Read from the file
char buffer[256];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("Error reading from file");
close(fd);
return EXIT_FAILURE;
}
// Null-terminate the buffer and print the content
buffer[bytes_read] = '\0';
printf("File content: %s\n", buffer);
// Close the file
if (close(fd) == -1) {
perror("Error closing file");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}