ti3_trashcan Muster

Reading time ~2 minutes

/* trashcan.c */

#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h> // für close
#include <string.h>

#define B_SIZE 2048
#define TRASH_PATH ".ti3_trashcan"

int mkfolder(void);
int move(char*, char*);
int del(char*);

int main (int argc, char* argv[])
{
    // validate parameters
    if (argc < 3)
    {
        printf("\nTo few arguments.\npattern:\n\n$ ./trashcan -p myfile\n\n");
        return 1;
    }

    // init parameters
    char* modus   = argv[1];
    char* file    = argv[2];

    // init string buffer
    char buffer[B_SIZE];
    for (int i = 0; i < sizeof(buffer); i++)
        buffer[i] = '\0';
    strcpy(buffer, TRASH_PATH);
    strcat(buffer, "/");
    strcat(buffer, file);

    // init trashcan
    mkfolder();

    // get mode
    if (modus[0] == '-')
    {
        switch(modus[1])
        {
        case 'p':
            move(file, buffer);
            break;
        case 'g':
            move(buffer, file);
            break;
        case 'r':
            del(buffer);
            break;
        default:
            printf("idents are: p {put} | g {get} | r {remove}\n");
        }
    }
    else
        printf("format: -<ident> <filename>\n");
    return 0;
}

// returns 0 on success, -1 on fail
int mkfolder(void)
{
    int tmp = open(TRASH_PATH, O_RDONLY);
    //wenn der ordner existiert, brich ab
    if (tmp != -1)
    {
        return -1;
    }
    close(tmp);
    mkdir(TRASH_PATH, 0666);
    return 0;
}

// returns 0 on success, -1 on fail
int move(char* source, char* target)
{
    int i = 0;

    // init string buffer
    char buffer[B_SIZE];
    for (int j = 0; j < sizeof(buffer); j++)
        buffer[j] = '\0';

    // added deletion of source to copy()
    int source_h = open(source, O_RDONLY);
    int target_h = open(target, O_WRONLY | O_CREAT | O_EXCL, 0666);
    if (target_h == -1 || source_h == -1)
    {
        close(source_h);
        close(target_h);
        perror("open");
        return -1;
    }

    read(source_h, buffer, sizeof(buffer));
    while(buffer[i] != '\0')
        i++;

    write(target_h, buffer, i);
    close(source_h);
    close(target_h);
    unlink(source);
    return 0;
}

// returns 0 on success, -1 on fail
int del(char* file)
{
    int file_h = open(file, O_RDWR);
    if (file_h == -1)
    {
        perror("open");
        return -1;
    }
    close(file_h);
    unlink(file);
	return 0;
}