Write a c program to copy files using system calls.
C program that copies a file using system calls, specifically open(), read(), and write(). This program takes the source file and destination file as command-line arguments.
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #define BUFFER_SIZE 1024 // Buffer size for file copy void copy_file(const char *src, const char *dest) { int src_fd, dest_fd; char buffer[BUFFER_SIZE]; ssize_t bytes_read, bytes_written; // Open source file for reading src_fd = open(src, O_RDONLY); if (src_fd == -1) { perror("Error opening source file"); exit(EXIT_FAILURE); } // Open/create destination file for writing dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (dest_fd == -1) { perror("Error opening/creating destination file"); close(src_fd); exit(EXIT_FAILURE); } // Copy the file content while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) { bytes_written = write(dest_fd, buffer, bytes_read); if (bytes_written != bytes_read) { perror("Error writing to destination file"); close(src_fd); close(dest_fd); exit(EXIT_FAILURE); } } // Check for read error if (bytes_read == -1) { perror("Error reading from source file"); } // Close the file descriptors close(src_fd); close(dest_fd); } int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]); exit(EXIT_FAILURE); } copy_file(argv[1], argv[2]); printf("File copied from %s to %s\n", argv[1], argv[2]); return 0; }