Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define BUFSIZE 1000
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int init_files(FILE **src, FILE **tmp, char *file_path);
- void print_file(FILE *src);
- int write(FILE *src, FILE **dest, char* file_path, int *lines);
- int memberOf(int val, int *array);
- int parse_input(int argc, char *argv[]);
- int main(int argc, char *argv[])
- {
- /* init */
- FILE *fptr_src;
- FILE *fptr_tmp;
- char *file_path = "./test.txt";
- char *buf = malloc(sizeof(char)*BUFSIZE);
- int *lines = malloc(sizeof(int)*100);
- int i;
- for (i = 0; i < 100; ++i) {
- lines[i] = -1;
- }
- if (init_files(&fptr_src, &fptr_tmp, file_path)) {
- exit(1);
- }
- if (argc > 1) {
- switch(parse_input(argc, argv)) {
- case 0:
- if (argv[2])
- fprintf(fptr_tmp, "%s\n", argv[2]);
- else
- printf("error: must supply arguemnt for add\n");
- break;
- case 1:
- print_file(fptr_tmp);
- break;
- case 2: ;
- int j;
- i = 2, j = 0;
- while(argv[i]) {
- lines[j++] = atoi(argv[i++]);
- }
- break;
- default:
- printf("command not regocognized\n");
- break;
- }
- } else {
- printf("no arguments given\n");
- }
- write(fptr_tmp, &fptr_src, file_path, lines);
- fclose(fptr_src);
- fclose(fptr_tmp);
- return 0;
- }
- /* input parsing */
- int parse_input(int argc, char *argv[])
- {
- const char *commands[] = { "add", "ls", "rm" , NULL };
- int i = 0;
- while (commands[i]) {
- if (!strcmp(commands[i++], argv[1])) {
- return i-1;
- }
- }
- return -1;
- }
- /* file operations */
- int init_files(FILE **src, FILE **tmp, char *file_path)
- {
- char *buf = malloc(sizeof(char)*BUFSIZE);
- *src = fopen(file_path, "r");
- *tmp = fopen("./.test.tmp", "w+");
- if (*src == NULL || *tmp == NULL) {
- perror("Error:");
- return 1;
- }
- rewind(*src);
- /* else, copy data into tmp */
- int i = 0;
- while(fgets(buf, BUFSIZE, *src)) {
- fprintf(*tmp, "%s", buf);
- }
- return 0;
- }
- void print_file(FILE *src)
- {
- char *buf = malloc(sizeof(char)*BUFSIZE);
- int i = 0;
- rewind(src);
- while(fgets(buf, BUFSIZE, src)) {
- printf("%d - %s", i++, buf);
- }
- }
- int write(FILE *src, FILE **dest, char *file_path, int *lines) {
- char *buf = malloc(sizeof(char)*BUFSIZE);
- fclose(*dest);
- *dest = fopen(file_path, "w+");
- if (*dest == NULL) {
- perror("Error: ");
- return 1;
- }
- rewind(src);
- int i = 0;
- while (fgets(buf, BUFSIZE, src)) {
- if (!memberOf(i++, lines)) {
- fprintf(*dest, "%s", buf);
- }
- }
- return 0;
- }
- int memberOf(int val, int *arr)
- {
- int i;
- for (i = 0; i < 100; ++i) {
- if (arr[i] == val) {
- return 1;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement