From b2d4b574ff9d39c833f91eec74bf567eb05d9430 Mon Sep 17 00:00:00 2001 From: Pu Cheng Date: Fri, 20 Nov 2026 05:49:41 +0800 Subject: [PATCH] out BUGFIX flush the current file before opening the new one in ly_out_filepath() The new file was opened (and truncated) before the current stream was closed. When it was the same file, the data still buffered in the current stream were written into it on fclose() and remained after the new data. Flush the current stream first; it is still closed only after the new file is opened. --- src/out.c | 3 ++- tests/utests/basic/test_inout.c | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/out.c b/src/out.c index 110bb724e..8adeaecff 100644 --- a/src/out.c +++ b/src/out.c @@ -372,8 +372,9 @@ ly_out_filepath(struct ly_out *out, const char *filepath) return out->method.fpath.filepath; } - /* replace filepath */ + /* replace filepath, the data written into the current file go there before the new file is created/opened */ f = out->method.fpath.f; + fflush(f); out->method.fpath.f = fopen(filepath, "wb"); if (!out->method.fpath.f) { LOGERR(NULL, LY_ESYS, "Failed to open file \"%s\" (%s).", filepath, strerror(errno)); diff --git a/tests/utests/basic/test_inout.c b/tests/utests/basic/test_inout.c index c5e1d5c9c..70dd6f996 100644 --- a/tests/utests/basic/test_inout.c +++ b/tests/utests/basic/test_inout.c @@ -372,6 +372,19 @@ test_output_filepath(void **UNUSED(state)) fclose(f1); ly_out_free(out, NULL, 1); + + /* data written before changing to the same file are not left in the file after the new data */ + assert_int_equal(LY_SUCCESS, ly_out_new_filepath(fp1, &out)); + assert_int_equal(LY_SUCCESS, ly_write(out, "previous data", 13)); + assert_ptr_equal(NULL, ly_out_filepath(out, fp1)); + assert_int_equal(LY_SUCCESS, ly_write(out, "new", 3)); + ly_print_flush(out); + assert_non_null(f1 = fopen(fp1, "rb")); + memset(buf, 0, sizeof buf); + assert_int_equal(3, fread(buf, 1, 30, f1)); + assert_string_equal("new", buf); + fclose(f1); + ly_out_free(out, NULL, 1); } static ssize_t