Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <dirent.h>
- #include <errno.h>
- #include <libgen.h>
- #include <string.h>
- #include <stdlib.h>
- int dir_exists(char* path);
- void copy(char* file1, char* file2);
- void move(char* filename);
- char* path = "/tmp/cmanchik/trash";
- int main(int argc, char *argv[]){
- if(dir_exists(path) < 1){
- int result = mkdir(path, 0777);
- printf("Result: %d\n", result);
- }
- if(argc == 1){
- printf("No arguments passed. Please pass in a file name\n");
- exit(1);
- }
- int i;
- for(i = 1; i < (argc); i++){
- struct stat sb;
- char * g = malloc(strlen(path)+ strlen(argv[i])+1);
- strcpy(g,path);
- strcat(g,"/");
- strcat(g,argv[i]);
- if (stat(g, &sb) == 0 && S_ISDIR(sb.st_mode))
- {
- struct dirent *de;
- DIR *dr = opendir(g);
- if (dr == NULL)
- {
- printf("Could not open current directory" );
- return 0;
- }
- while ((de = readdir(dr)) != NULL){
- if (strcmp(de->d_name,".") == 0 || strcmp(de->d_name,"..") == 0){
- continue;
- }else{
- printf("File %s\n",de->d_name);
- char* t = malloc(strlen("/tmp/cmanchik/trash/") + strlen(argv[i]) + strlen(de->d_name) + 1);
- strcpy(t, "/tmp/cmanchik/trash/");
- strcat(t, argv[i]);
- strcat(t, "/");
- strcat(t, de->d_name);
- move(t);
- }
- }
- closedir(dr);
- }
- else{
- char * t = malloc(strlen("/tmp/cmanchik/trash/") + strlen(argv[i]));
- strcpy(t, "/tmp/cmanchik/trash/");
- strcat(t,argv[i]);
- move(t);
- }
- }
- }
- void move(char* filename){
- if(access(filename, F_OK) == -1){
- printf("File does not exist\n");
- }
- char* base = basename(filename);
- char p[4096];
- getcwd(p,sizeof(p));
- char* temp_path = malloc(strlen(p) + strlen(base) + 1);
- strcpy(temp_path, p);
- strcat(temp_path, "/");
- strcat(temp_path, base);
- printf("Filename: %s\n",filename);
- printf("%s\n", temp_path);
- int ret = rename(filename, temp_path);
- if(ret == 0){
- printf("Successfully moved file\n");
- }else{
- copy(filename, temp_path);
- unlink(filename);
- }
- }
- void copy(char* file1, char* file2){
- FILE *ptr1, *ptr2;
- ptr1 = fopen(file1, "r");
- if(ptr1 == NULL){
- printf("First Cannot open file\n");
- }
- ptr2 = fopen(file2, "w");
- if(ptr2 == NULL){
- printf("Second Cannot open file\n");
- }
- char c = fgetc(ptr1);
- while(c != EOF){
- fputc(c, ptr2);
- c = fgetc(ptr1);
- }
- fclose(ptr1);
- fclose(ptr2);
- }
- int dir_exists(char* path){
- DIR* dir = opendir(path);
- if(dir){
- closedir(dir);
- return 1;
- }
- else if(ENOENT == errno){
- return 0;
- }
- else{
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement