diff options
author | June McEnroe <june@causal.agency> | 2018-11-22 22:04:41 -0500 |
---|---|---|
committer | June McEnroe <june@causal.agency> | 2018-11-22 22:04:41 -0500 |
commit | 34532a56421ef19a5a5bc5c93068fb26f4c29187 (patch) | |
tree | 2b63a1df063087ffa7fbed09a85e9812f4f6f096 /bin/edi/file.c | |
parent | Simplify edi file reading (diff) | |
download | src-34532a56421ef19a5a5bc5c93068fb26f4c29187.tar.gz src-34532a56421ef19a5a5bc5c93068fb26f4c29187.zip |
Add fileWrite for edi
Diffstat (limited to 'bin/edi/file.c')
-rw-r--r-- | bin/edi/file.c | 32 |
1 files changed, 31 insertions, 1 deletions
diff --git a/bin/edi/file.c b/bin/edi/file.c index 834730b1..91479ee6 100644 --- a/bin/edi/file.c +++ b/bin/edi/file.c @@ -14,7 +14,6 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include <assert.h> #include <err.h> #include <errno.h> #include <stdio.h> @@ -80,3 +79,34 @@ void fileRead(struct File *file) { fclose(stream); } + +// TODO: Error handling. +void fileWrite(struct File *file) { + if (!file->path) return; + + FILE *stream = fopen(file->path, "w"); + if (!stream) err(EX_CANTCREAT, "%s", file->path); + + const struct Table *table = logTable(&file->log); + if (!table) errx(EX_SOFTWARE, "fileWrite: no table"); + + char buf[BufferCap]; + mbstate_t state = StateInit; + for (size_t i = 0; i < table->len; ++i) { + struct Slice slice = table->slices[i]; + while (slice.len) { + size_t mbsLen = wcsnrtombs( + buf, &slice.ptr, slice.len, sizeof(buf), &state + ); + if (mbsLen == (size_t)-1) err(EX_DATAERR, "%s", file->path); + slice.len -= slice.ptr - table->slices[i].ptr; + + fwrite(buf, 1, mbsLen, stream); + if (ferror(stream)) err(EX_IOERR, "%s", file->path); + } + } + file->clean = file->log.state; + + fclose(stream); + if (ferror(stream)) err(EX_IOERR, "%s", file->path); +} |