Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/stream.c
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,9 @@ asdf_stream_t *asdf_stream_from_fp(

asdf_stream_t *asdf_stream_from_file(asdf_context_t *ctx, const char *filename, bool is_writeable) {
FILE *file = fopen(filename, is_writeable ? "r+b" : "rb");
/* r+b requires the file to exist; create it if it doesn't */
if (!file && is_writeable && errno == ENOENT)
file = fopen(filename, "w+b");
if (!file) {
asdf_context_error_set_system(ctx, errno, __FILE__, __LINE__);
return NULL;
Expand Down
24 changes: 24 additions & 0 deletions tests/test-file.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <stc/cstr.h>

Expand Down Expand Up @@ -791,6 +792,28 @@ MU_TEST(write_custom_tag_handle) {
}


/** Regression test: writing to a path that does not yet exist should succeed */
MU_TEST(write_to_nonexistent_file) {
const char *filename = get_temp_file_path(fixture->tempfile_prefix, ".asdf");
/* get_temp_file_path pre-creates the file; remove it so the write must create it */
assert_int(unlink(filename), ==, 0);

asdf_file_t *file = asdf_open(NULL);
assert_not_null(file);
assert_int(asdf_set_string0(file, "key", "value"), ==, ASDF_VALUE_OK);
assert_int(asdf_write_to(file, filename), ==, 0);
asdf_close(file);

file = asdf_open(filename, "r");
assert_not_null(file);
const char *val = NULL;
assert_int(asdf_get_string0(file, "key", &val), ==, ASDF_VALUE_OK);
assert_string_equal(val, "value");
asdf_close(file);
return MUNIT_OK;
}


/** Regression test for a double-free that could occur in this case */
MU_TEST(test_asdf_set_value_double_free) {
const char *filename = get_temp_file_path(fixture->tempfile_prefix, ".asdf");
Expand Down Expand Up @@ -837,6 +860,7 @@ MU_TEST_SUITE(
MU_RUN_TEST(write_minimal),
MU_RUN_TEST(write_minimal_empty_tree),
MU_RUN_TEST(write_custom_tag_handle),
MU_RUN_TEST(write_to_nonexistent_file),
MU_RUN_TEST(test_asdf_set_value_double_free)
);

Expand Down
Loading