summaryrefslogtreecommitdiff
path: root/simplenote.c
blob: a89df2c00b874fedf2bfb08536ddb36222693d2a (plain)
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
68
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

void usage(const char *prog_name, char *filename)
{
  printf("Usage: %s <data to add to %s>\n", prog_name, filename);
  exit(0);
}

void fatal(char *);
void *ec_malloc(unsigned int);

int main(int argc, const char *argv[])
{
  int fd;
  char *buffer, *datafile;

  buffer = (char *) ec_malloc(100);
  datafile = (char *) ec_malloc(20);
  strcpy(datafile, "/tmp/notes");

  if (argc < 2)
    usage(argv[0], datafile);

  strcpy(buffer, argv[1]);
  printf("[DEBUG] buffer @ %p: \'%s\'\n", buffer, buffer);
  printf("[DEBUG] datafile @ %p: \'%s\'\n", datafile, datafile);

  strncat(buffer, "\n", 1);

  fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
  if (fd == -1)
    fatal("in main() while opening file");

  printf("[DEBUG] file descriptor is %d\n", fd);

  if (write(fd, buffer, strlen(buffer)) == -1)
    fatal("in main() while writing buffer to file");

  if(close(fd) == -1)
    fatal("in main() while closing file");

  printf("note has been saved.\n");
  free(buffer);
  free(datafile);
  return 0;
}

void fatal(char *message)
{
  char error_message[100];
  strcpy(error_message, "[!!] Fatal Error ");
  strncat(error_message, message, 83);
  perror(error_message);
  exit(-1);
}

void *ec_malloc(unsigned int size)
{
  void *ptr;
  ptr = malloc(size);
  if (ptr == NULL) 
    fatal("in ec_malloc() on memory allocation");
  return ptr;
}