aboutsummaryrefslogtreecommitdiffstats
path: root/rm.c
blob: 00dbd762e4e43a816a8f9a966f3c32ef3781d701 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/* TODO make a recursive flag */

int rm(char *fn, int frc, int ask, int expAsk);

int
rm(char *fn, int frc, int ask, int prompt)
{
  FILE *f;
  int sz;
  char yn;

  /* get length of fn and check if it exists */
  if ((f = fopen(fn, "r"))) {
    fseek(f, 0L, SEEK_END);
    sz = ftell(f);
  } else {
    fprintf(stderr, "fn '%s' doesn't exist!\n", fn);
    return 1;
  }

  /* confirm deletion(s) when ask is on, and size is over 0 */
  if (prompt && !frc || (ask && sz > 0)) {
    printf("Do you want to delete %s? ", fn);
    yn = getchar();

    if (yn == 'y')
      remove(fn);
  } else
    remove(fn);

  return 0;
}

int
main(int argc, char *argv[])
{
  int ask = 1; /* confirm deletion */
  int prompt = 0; /* explicitly confirm deletion */
  int frc = 0; /* force deletion */
  int c;

	while ((c = getopt(argc, argv, "efh")) != -1) {
    switch (c) {
      case 'i': prompt = 1; break;
      case 'f': frc = 1; ask = 0; break;
      case 'h': goto usage; break;
      default: printf("run %s -h for help\n", argv[0]); return 1; break;
    }
	}

  /* for each argument */
  for (int i = 1; i < argc; i++) {
    while (strncmp(argv[i], "-", 1) == 0) /* ignore args that start with - */
      i++;
    rm(argv[i], frc, ask, prompt);
  }

  return 0;

usage:
  printf("Usage: %s -option(s) file(s)\n", argv[0]);
  printf("\n\t-i prompt user for deletion of every file\n\t-f force deletion, does not ask for confirmation\n\t-h shows this help message\n");
}