Practical Coding Examples
1. File Size Analyzer
Bash Script for Directory Size Calculation
#!/bin/bash
analyze_directory_size() {
local dir_path=$1
echo "Analyzing directory: $dir_path"
## Calculate total size and file count
total_size=$(du -sh "$dir_path")
file_count=$(find "$dir_path" -type f | wc -l)
echo "Total Size: $total_size"
echo "Total Files: $file_count"
}
analyze_directory_size "/home/labex/documents"
2. Python File Organizer
Automatic File Classification Script
import os
import shutil
def organize_files(source_dir):
## File type mapping
file_types = {
'Images': ['.jpg', '.png', '.gif'],
'Documents': ['.pdf', '.docx', '.txt'],
'Videos': ['.mp4', '.avi', '.mkv']
}
## Create destination directories
for category in file_types:
os.makedirs(os.path.join(source_dir, category), exist_ok=True)
## Iterate and move files
for filename in os.listdir(source_dir):
filepath = os.path.join(source_dir, filename)
if os.path.isfile(filepath):
file_ext = os.path.splitext(filename)[1].lower()
for category, extensions in file_types.items():
if file_ext in extensions:
dest_path = os.path.join(source_dir, category, filename)
shutil.move(filepath, dest_path)
break
organize_files("/home/labex/downloads")
3. C Program: Recursive File Search
Finding Large Files
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#define MAX_PATH 1024
#define SIZE_THRESHOLD 10485760 // 10MB
void find_large_files(const char *dir_path) {
DIR *dir;
struct dirent *entry;
char path[MAX_PATH];
struct stat file_stat;
dir = opendir(dir_path);
if (dir == NULL) {
perror("Unable to open directory");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
if (stat(path, &file_stat) == 0) {
if (file_stat.st_size > SIZE_THRESHOLD) {
printf("Large File: %s (Size: %ld bytes)\n",
path, file_stat.st_size);
}
}
}
// Recursive directory traversal can be added here
}
closedir(dir);
}
int main() {
find_large_files("/home/labex/documents");
return 0;
}
Traversal Strategies Comparison
Strategy |
Complexity |
Performance |
Use Case |
Bash Scripts |
Low |
Fast for simple tasks |
Quick file operations |
Python |
Medium |
Flexible, readable |
Data processing |
C Programming |
High |
Best performance |
System-level operations |
Workflow Visualization
graph TD
A[Start Directory Scan] --> B{Analyze File Types}
B --> C[Categorize Files]
C --> D{Check File Size}
D --> E[Move/Process Files]
E --> F[Generate Report]
Best Practices
- Handle file permissions
- Implement error checking
- Use appropriate traversal method
- Consider performance and memory usage
By exploring these practical examples on LabEx, you'll develop robust skills in Linux directory traversal and file management techniques.