Practical Copying Techniques
Command-Line File Copying Methods
Basic cp
Command Options
Option |
Description |
Example |
-r |
Recursive copy |
cp -r source_dir destination_dir |
-p |
Preserve attributes |
cp -p file1.txt file2.txt |
-v |
Verbose mode |
cp -v source.txt destination.txt |
-i |
Interactive mode |
cp -i existing_file new_file |
Advanced Copying Techniques
Using rsync
for Efficient Copying
## Basic rsync syntax
rsync [options] source destination
## Example: Synchronize directories
rsync -avz /source/directory/ /destination/directory/
Handling Large File Transfers
graph TD
A[Prepare File Transfer] --> B[Check Disk Space]
B --> C[Select Appropriate Method]
C --> D[Choose Transfer Tool]
D --> E[Monitor Transfer Progress]
E --> F[Verify File Integrity]
Specialized Copying Scenarios
Network File Copying
## SCP (Secure Copy)
scp source_file user@remote_host:/destination/path
## SFTP (Secure File Transfer Protocol)
sftp user@remote_host
Error Handling and Validation
Implementing Robust Copy Mechanisms
#include <stdio.h>
#include <errno.h>
int robust_file_copy(const char *source, const char *destination) {
FILE *src, *dest;
char buffer[4096];
size_t bytes_read;
// Open source file
src = fopen(source, "rb");
if (src == NULL) {
perror("Error opening source file");
return -1;
}
// Open destination file
dest = fopen(destination, "wb");
if (dest == NULL) {
perror("Error creating destination file");
fclose(src);
return -1;
}
// Copy file contents
while ((bytes_read = fread(buffer, 1, sizeof(buffer), src)) > 0) {
if (fwrite(buffer, 1, bytes_read, dest) != bytes_read) {
perror("Error writing to destination file");
fclose(src);
fclose(dest);
return -1;
}
}
// Check for read errors
if (ferror(src)) {
perror("Error reading source file");
fclose(src);
fclose(dest);
return -1;
}
fclose(src);
fclose(dest);
return 0;
}
Method |
Speed |
Reliability |
Use Case |
cp |
Low |
Medium |
Small files |
rsync |
High |
High |
Large directories |
dd |
Medium |
High |
Disk imaging |
Best Practices
- Always verify file integrity
- Use appropriate tools for specific scenarios
- Consider network bandwidth and storage limitations
Monitoring and Logging
Tracking File Transfer Progress
## Using dd with progress
dd if=/source/file of=/destination/file status=progress
Note: LabEx recommends mastering these techniques to become proficient in Linux file management and transfer operations.
Conclusion
Practical file copying goes beyond simple command execution, requiring understanding of various tools, error handling, and performance optimization strategies.