System calls Unix linux

PHOTO EMBED

Sat Mar 22 2025 05:00:27 GMT+0000 (Coordinated Universal Time)

Saved by @Hitha

2. Write programs using the I/O system calls of UNIX/LINUX operating system(open, read, write, close, fcntl, seek, stat, opendir, readdir)Program:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>int main() {// Open a source file for readingint source_fd = open("source.txt", O_RDONLY);if (source_fd == -1) {perror("Failed to open source.txt");exit(1);}// Create or open a destination file for writingint dest_fd = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);if (dest_fd == -1) {perror("Failed to open destination.txt");close(source_fd); // Close the source fileexit(1);}// Read from the source file and write to the destination filechar buffer[4096]; // A buffer to hold datassize_t nread;while ((nread = read(source_fd, buffer, sizeof(buffer))) > 0) {if (write(dest_fd, buffer, nread) != nread) {perror("Write error");break;}}// Check if there was an error during readingif (nread < 0) {perror("Read error");}// Close both filesclose(source_fd);close(dest_fd);return 0;}Explanation:In this program, we use the following system calls:Open : Opens files.Read : Reads data from a file.Write : Writes data to a file.Close : Closes open files.Perror : Prints error messages.Fcntl : A system call for file control is not used in this example but is available for other file operations.Seek : File seeking operations are not used in this basic example.Stat : File stat functions are not used here.Opendir : Opening directories is not used in this example.Readdir : Reading directories is not used in this example.
content_copyCOPY