Certainly! Here's a more concise version of your C program for copying the contents of source.txt to destination.txt. This version maintains essential error handling while reducing the overall code length:
c Copy code
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main() {
int src_fd = open("source.txt", O_RDONLY);
if (src_fd < 0) { perror("Open source"); exit(EXIT_FAILURE); }
int dest_fd = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd < 0) { perror("Open destination"); close(src_fd); exit(EXIT_FAILURE); }
char buffer[BUFFER_SIZE];
ssize_t bytes;
while ((bytes = read(src_fd, buffer, sizeof(buffer))) > 0) {
if (write(dest_fd, buffer, bytes) != bytes) {
perror("Write error");
close(src_fd);
close(dest_fd);
exit(EXIT_FAILURE);
}
}
if (bytes < 0) {
perror("Read error");
} else {
printf("File copied successfully!\n");
}
close(src_fd);
close(dest_fd);
return 0;
}
Explanation of Changes:
Macro for Buffer Size :
Defined BUFFER_SIZE for clarity and easier adjustments.
Simplified Error Messages :
Shortened perror messages for brevity while maintaining clarity.
Combined Declarations :
Merged variable declarations where appropriate to reduce lines.
Error Handling in Write Operation :
Added a check to ensure that the number of bytes written matches the number read, ensuring data integrity.
Conditional Success Message :
Moved the success message inside the conditional to ensure it's only printed when no read errors occur.
Consistent Indentation and Formatting :
Improved readability with consistent indentation.
Alternative Approach Using fopen and Standard I/O
If you prefer using higher-level file operations with fopen, fread, and fwrite, here's an alternative concise version:
c Copy code
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main() {
FILE *src = fopen("source.txt", "rb");
if (!src) { perror("Open source"); exit(EXIT_FAILURE); }
FILE *dest = fopen("destination.txt", "wb");
if (!dest) { perror("Open destination"); fclose(src); exit(EXIT_FAILURE); }
char buffer[BUFFER_SIZE];
size_t bytes;
while ((bytes = fread(buffer, 1, sizeof(buffer), src)) > 0) {
if (fwrite(buffer, 1, bytes, dest) != bytes) {
perror("Write error");
fclose(src);
fclose(dest);
exit(EXIT_FAILURE);
}
}
if (ferror(src)) {
perror("Read error");
} else {
printf("File copied successfully!\n");
}
fclose(src);
fclose(dest);
return 0;
}
Benefits of Using fopen and Standard I/O:
Simplicity : Higher-level functions are often easier to use and understand.
Portability : Standard I/O functions are more portable across different operating systems.
Buffered I/O : Provides buffering, which can improve performance for certain I/O operations.
Choose the approach that best fits your requirements and familiarity with low-level vs. high-level file operations.