Public feed #724411

Unnamed

public text v1 · immutable
Raw Edit
·published 2007-10-03 15:56 UTC
rendered paste body
// cleana.c
// Removes lines containing 'key' from 'file' with 'exception'

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

main(int argc, char *argv[])
        {
        FILE *fd;
        FILE *cleanfd;
        char buffer[200],filec[100];

        if (argc < 3){
                printf("Usage: ./cleana file key [exception]\n");
                exit(1);
        }

        strcat(filec, argv[1]);
        strcat(filec,".cleaned");

// OPEN FILE

        if ((fd = fopen(argv[1], "r")) == NULL){
        printf("Fatal: Cannot open file!\n");
        exit(1);
        }
        if ((cleanfd = fopen(filec, "w+")) == NULL){
        printf("Fatal: Cannot open/create clean file!\n");
        exit(1);
        }

// CLEAN FILE

while((fgets(buffer, sizeof(buffer), fd)) != NULL){

        if ((strstr(buffer, argv[2])) == NULL){
                fputs(buffer, cleanfd);
        } else {
                if (argc == 4){
                        if ((strstr(buffer, argv[3])) != NULL){
                                 fputs(buffer, cleanfd);
                        }
                }
        }
}

        fclose(cleanfd);
        fclose(fd);

        if ((execl("/bin/", "mv", filec, argv[1])) == -1) perror("execl");
        printf("Operation completed!\n");

} // END MAIN