commit c04a3d6846cb3ef7bad9300519a5bb4e1c2a2568
parent 9cbc8b6361d405aebca8c8f9f50dd02d95500c73
Author: brookjeynes <me@brookjeynes.dev>
Date: Thu, 11 Jun 2026 14:15:06 +1000
fix: handle runtime errors
Diffstat:
| M | main.c | | | 49 | +++++++++++++++++++++++++++++++++++++++++++------ |
1 file changed, 43 insertions(+), 6 deletions(-)
diff --git a/main.c b/main.c
@@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <errno.h>
#include <unistd.h>
struct options {
@@ -97,22 +98,58 @@ int main(int argc, char *argv[]) {
FILE *f = fopen(title_to_file, "wx");
if (f == NULL) {
- fprintf(stderr, "err: failed to open file. the file may already exist\n");
+ fprintf(stderr, "err: failed to open file: %s\n", strerror(errno));
exit(1);
}
+ int write_failed = 0;
+ int write_errno = 0;
if (cli_args.priority != '\0') {
- fprintf(f, "(%c) ", cli_args.priority);
+ if (fprintf(f, "(%c) ", cli_args.priority) < 0) {
+ write_failed = 1;
+ write_errno = errno;
+ }
}
- fprintf(f, "%s", cli_args.title);
+ if (fprintf(f, "%s", cli_args.title) < 0) {
+ if (!write_failed) {
+ write_failed = 1;
+ write_errno = errno;
+ }
+ }
if (cli_args.properties != NULL) {
- fprintf(f, " %s", cli_args.properties);
+ if (fprintf(f, " %s", cli_args.properties) < 0) {
+ if (!write_failed) {
+ write_failed = 1;
+ write_errno = errno;
+ }
+ }
+ }
+
+ if (fprintf(f, "\n") < 0) {
+ if (!write_failed) {
+ write_failed = 1;
+ write_errno = errno;
+ }
}
- fprintf(f, "\n");
- fclose(f);
+ int close_failed = 0;
+ int close_errno = 0;
+ if (fclose(f) != 0) {
+ close_failed = 1;
+ close_errno = errno;
+ }
+
+ if (write_failed) {
+ fprintf(stderr, "err: failed to write file: %s\n", strerror(write_errno));
+ exit(1);
+ }
+
+ if (close_failed) {
+ fprintf(stderr, "err: failed to close file: %s\n", strerror(close_errno));
+ exit(1);
+ }
char *editor = getenv("EDITOR");
if (editor == NULL) {