1 /* src/common/readwrite.c */
4 #include <stddef.h> /* size_t */
5 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, UINT32_MAX */
6 #include <stdio.h> /* FILE, fseek(), sprintf(), fgets(), fgetc(), ferror(),
7 * fputc(), fwrite(), fclose(), fopen()
9 #include <string.h> /* strlen() */
10 #include <unistd.h> /* for access(), unlink() */
11 #include "rexit.h" /* exit_err(), exit_trouble() */
15 extern FILE * try_fopen(char * path, char * mode, char * f)
17 char * msg1 = "Trouble in ";
18 char * msg2 = " with fopen() (mode '";
19 char * msg3 = "') on path '";
21 uint16_t size = strlen(msg1) + strlen(msg2) + strlen(msg3) + strlen(msg4)
22 + strlen(f) + strlen(path) + strlen(mode) + 1;
24 sprintf(msg, "%s%s%s%s%s%s%s", msg1, f, msg2, mode, msg3, path, msg4);
25 FILE * file_p = fopen(path, mode);
26 exit_err(NULL == file_p, msg);
32 extern void try_fclose(FILE * file, char * f)
34 exit_trouble(fclose(file), f, "fclose()");
39 extern void try_fwrite(void * ptr, size_t size, size_t nmemb, FILE * stream,
42 exit_trouble(0 == fwrite(ptr, size, nmemb, stream), f, "fwrite()");
47 extern void try_fputc(uint8_t c, FILE * file, char * f)
49 exit_trouble(EOF == fputc(c, file), f, "fputc()");
54 extern int try_fgetc(FILE * file, char * f)
56 int test = fgetc(file);
57 exit_trouble(EOF == test && ferror(file), f, "fgetc()");
63 extern char * try_fgets(char * line, int linemax, FILE * file, char * f)
65 char * test = fgets(line, linemax, file);
66 exit_trouble(NULL == test && ferror(file), f, "fgets()");
72 extern void try_fclose_unlink_rename(FILE * file, char * p1, char * p2,
76 char * msg1 = "Trouble in ";
78 if (!access(p2, F_OK))
80 char * msg2 = " with unlink() on path '";
81 uint16_t size = strlen(msg1) + strlen(msg2) + strlen(msg4)
82 + strlen(f) + strlen(p2) + 1;
84 sprintf(msg, "%s%s%s%s%s", msg1, f, msg2, p2, msg4);
85 exit_err(unlink(p2), msg);
87 char * msg2 = " with rename() from '";
88 char * msg3 = "' to '";
89 uint16_t size = strlen(msg1) + strlen(f) + strlen(msg2) + strlen(p1)
90 + strlen(msg3) + strlen(p2) + strlen(msg4) + 1;
92 sprintf(msg, "%s%s%s%s%s%s%s", msg1, f, msg2, p1, msg3, p2, msg4);
93 exit_err(rename(p1, p2), msg);
98 extern uint32_t textfile_width(FILE * file)
100 char * f_name = "textfile_width()";
102 uint32_t c_count = 0;
103 uint32_t linemax = 0;
106 c = try_fgetc(file, f_name);
111 exit_trouble(UINT32_MAX == c_count, f_name, "too large text file line");
115 if (c_count > linemax)
122 if (0 == linemax && 0 < c_count) /* Handle files that consist of only one */
123 { /* line / lack newline chars. */
126 exit_trouble(-1 == fseek(file, 0, SEEK_SET), f_name, "fseek()");