Prompt Title: Copy Files in Linux.

Created 1 year ago
Votes 0
Views 54 times
0

Prompt Detail:

To make a copy of "zing.h" and "zing.o" files from the directory "/home/oslab/code/zing" to the directory "/home/oslab/oslab182" using open(), read(), and close() system calls in Linux, you can create a C program like this:

scss
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main() { int fd1, fd2, nbytes; char buffer[1024]; char *file1 = "/home/oslab/code/zing/zing.h"; char *file2 = "/home/oslab/code/zing/zing.o"; char *destDir = "/home/oslab/oslab182/"; // Open source files fd1 = open(file1, O_RDONLY); if (fd1 == -1) { perror("Error opening file1"); exit(EXIT_FAILURE); } fd2 = open(file2, O_RDONLY); if (fd2 == -1) { perror("Error opening file2"); exit(EXIT_FAILURE); } // Open destination directory for writing char destFile1[1024], destFile2[1024]; sprintf(destFile1, "%s%s", destDir, "zing.h"); sprintf(destFile2, "%s%s", destDir, "zing.o"); int dest1 = open(destFile1, O_CREAT | O_WRONLY, 0644); if (dest1 == -1) { perror("Error opening destination file1"); exit(EXIT_FAILURE); } int dest2 = open(destFile2, O_CREAT | O_WRONLY, 0644); if (dest2 == -1) { perror("Error opening destination file2"); exit(EXIT_FAILURE); } // Read data from source files and write to destination files while ((nbytes = read(fd1, buffer, sizeof(buffer))) > 0) { write(dest1, buffer, nbytes); } while ((nbytes = read(fd2, buffer, sizeof(buffer))) > 0) { write(dest2, buffer, nbytes); } // Close all files close(fd1); close(fd2); close(dest1); close(dest2); printf("Files copied successfully!\n"); return 0; }

This program opens the source files using the open() system call with O_RDONLY flag to read data from the files. It then creates new files in the destination directory using the open() system call with O_CREAT and O_WRONLY flags to write data to the files.

It reads data from the source files using the read() system call and writes it to the destination files using the write() system call. It repeats this process until all the data has been read and written.

Finally, it closes all the files using the close() system call.

To compile this program, save it to a file named "copy.c" and run the following command in the terminal:

go
gcc copy.c -o copy

This will create an executable file named "copy". Then, to run the program, type:

bash
./copy

This will copy the "zing.h" and "zing.o" files from "/home/oslab/code/zing" to "/home/oslab/oslab182" using open(), read(), and close() system calls in Linux.

avatar
Michalis
Shared 1 prompt
Created 1 year ago

Leave a Comment