diff --git a/README.md b/README.md new file mode 100644 index 0000000..d521fca --- /dev/null +++ b/README.md @@ -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)) + diff --git a/fd.cpp b/fd.cpp new file mode 100644 index 0000000..c4a73fd --- /dev/null +++ b/fd.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +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; +}