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:
parent
d3a10d7190
commit
f332b0868a
2 changed files with 62 additions and 0 deletions
10
README.md
Normal file
10
README.md
Normal file
|
@ -0,0 +1,10 @@
|
|||
# tmp.c
|
||||
|
||||
Hacking around with C/C++ basics to get myself comfortable and up to speed.
|
||||
To a large extent, making myself attempt to do small projects in C/C++ as a default.
|
||||
|
||||
## Links
|
||||
|
||||
- [GNU C Library manual](https://www.gnu.org/software/libc/manual/html_node/index.html)
|
||||
- [21 Century C++ by Bjarne Stroustrup](https://cacm.acm.org/blogcacm/21st-century-c/) ([joplin copy](joplin://x-callback-url/openNote?id=8bea21d4cd134ceeaeeaff01f33427cd))
|
||||
|
52
fd.cpp
Normal file
52
fd.cpp
Normal 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;
|
||||
}
|
Loading…
Add table
Reference in a new issue