Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <dirent.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <sys/wait.h>
- #define MAX_PATH_LENGTH 4096
- #define MAX_FILENAME_LENGTH 256
- #define MAX_CHILD_PROCESSES 10
- typedef struct {
- char filename[MAX_FILENAME_LENGTH];
- off_t size;
- } FileInfo;
- int compareBySize(const void *a, const void *b) {
- return ((FileInfo *)a)->size - ((FileInfo *)b)->size;
- }
- int compareByName(const void *a, const void *b) {
- return strcmp(((FileInfo *)a)->filename, ((FileInfo *)b)->filename);
- }
- void copyFile(const char *sourcePath, const char *destPath) {
- // ... (unchanged)
- }
- void sortAndCopyFiles(const char *dirPath, int sortBy, const char *destPath, int maxProcesses) {
- DIR *dir = opendir(dirPath);
- if (dir == NULL) {
- perror("Error opening directory");
- exit(EXIT_FAILURE);
- }
- struct dirent *entry;
- struct stat fileInfo;
- int numProcesses = 0;
- int numFiles = 0;
- FileInfo *files = malloc(MAX_CHILD_PROCESSES * sizeof(FileInfo));
- while ((entry = readdir(dir)) != NULL) {
- if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
- continue;
- char filePath[MAX_PATH_LENGTH];
- snprintf(filePath, sizeof(filePath), "%s/%s", dirPath, entry->d_name);
- if (lstat(filePath, &fileInfo) == -1) {
- perror("Error getting file info");
- exit(EXIT_FAILURE);
- }
- if (S_ISREG(fileInfo.st_mode)) {
- strncpy(files[numFiles].filename, entry->d_name, MAX_FILENAME_LENGTH - 1);
- files[numFiles].size = fileInfo.st_size;
- numFiles++;
- if (numFiles >= MAX_CHILD_PROCESSES) {
- qsort(files, numFiles, sizeof(FileInfo), (sortBy == 1) ? compareBySize : compareByName);
- for (int i = 0; i < numFiles; i++) {
- pid_t childPid = fork();
- if (childPid == -1) {
- perror("Error forking process");
- exit(EXIT_FAILURE);
- }
- if (childPid == 0) { // Child process
- printf("PID: %d, Path: %s, Filename: %s, Size: %ld bytes\n", getpid(), filePath, files[i].filename, files[i].size);
- char destFilePath[MAX_PATH_LENGTH];
- snprintf(destFilePath, sizeof(destFilePath), "%s/%s", destPath, files[i].filename);
- copyFile(filePath, destFilePath);
- exit(EXIT_SUCCESS);
- } else { // Parent process
- numProcesses++;
- if (numProcesses >= maxProcesses) {
- wait(NULL); // Wait for any child process to finish
- numProcesses--;
- }
- }
- }
- numFiles = 0;
- }
- }
- }
- closedir(dir);
- free(files);
- }
- int main(int argc, char *argv[]) {
- // ... (unchanged)
- int sortBy = atoi(argv[2]);
- if (sortBy != 1 && sortBy != 2) {
- fprintf(stderr, "Invalid sort criteria. Use 1 for sorting by size or 2 for sorting by name.\n");
- exit(EXIT_FAILURE);
- }
- // ... (unchanged)
- sortAndCopyFiles(dirPath, sortBy, destPath, maxProcesses);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement