readwriteopenclose
Fri Jun 07 2024 04:50:13 GMT+0000 (Coordinated Universal Time)
Saved by
@prabhas
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int main() {
int sourceFile, destFile;
ssize_t bytesRead, bytesWritten;
char buffer[BUFFER_SIZE];
// Open source file
sourceFile = open("source.txt", O_RDONLY);
if (sourceFile == -1) {
perror("Error opening source file");
exit(EXIT_FAILURE);
}
// Open destination file
destFile = open("dest.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (destFile == -1) {
perror("Error opening destination file");
close(sourceFile);
exit(EXIT_FAILURE);
}
// Read from source and write to destination
while ((bytesRead = read(sourceFile, buffer, BUFFER_SIZE)) > 0) {
bytesWritten = write(destFile, buffer, bytesRead);
if (bytesWritten != bytesRead) {
perror("Error writing to destination file");
close(sourceFile);
close(destFile);
exit(EXIT_FAILURE);
}
}
if (bytesRead == -1) {
perror("Error reading from source file");
}
// Close files
close(sourceFile);
close(destFile);
return 0;
}
content_copyCOPY
Comments