diff options
| author | mo khan <mo@mokhan.ca> | 2014-07-22 21:34:55 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2014-07-22 21:34:55 -0600 |
| commit | 979e358c31687184096594a536e43b0a9f77acc4 (patch) | |
| tree | bf964a46fef60db58ef6cc9228dcd01d926285e9 | |
| parent | 978cf6f2740be51428b41309c49dc91a8254ed96 (diff) | |
add example to write a file using a file descriptor.
| -rw-r--r-- | simplenote.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/simplenote.c b/simplenote.c new file mode 100644 index 0000000..a89df2c --- /dev/null +++ b/simplenote.c @@ -0,0 +1,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; +} |
