Skip to content

Commit

Permalink
ansi: Handle empty strings correctly in fputs
Browse files Browse the repository at this point in the history
Also adds a test for fputs.
  • Loading branch information
lzcunt committed Jan 30, 2025
1 parent 65b8589 commit 1e4c032
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
3 changes: 2 additions & 1 deletion options/ansi/generic/stdio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -934,7 +934,8 @@ int fputc(int c, FILE *stream) {
}

int fputs_unlocked(const char *__restrict string, FILE *__restrict stream) {
if(fwrite_unlocked(string, strlen(string), 1, stream) != 1)
size_t length = strlen(string);
if (length != 0 && fwrite_unlocked(string, length, 1, stream) != 1)
return EOF;
return 1;
}
Expand Down
41 changes: 41 additions & 0 deletions tests/ansi/fputs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <assert.h>
#include <stdio.h>
#include <string.h>

#ifdef USE_HOST_LIBC
#define TEST_FILE "fputs-host-libc.tmp"
#else
#define TEST_FILE "fputs.tmp"
#endif

int main() {
FILE *file;
char str[] = "mlibc fputs test";
char buffer[100];

// Clear the buffer to zero.
memset(buffer, 0, sizeof(buffer));

// Open the file for writing.
file = fopen(TEST_FILE, "w");
assert(file);

// Verify that we can write an empty string.
assert(fputs("", file) != EOF);

// Write string, flush and close.
assert(fputs(str, file) != EOF);
fflush(file);
fclose(file);

// Open the file for reading.
file = fopen(TEST_FILE, "r");
assert(file);

// Verify that we read back the written string and close.
assert(fread(buffer, 1, sizeof(str) - 1, file));
assert(!strcmp(buffer, str));
fclose(file);

return 0;
}
1 change: 1 addition & 0 deletions tests/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ all_test_cases = [
'ansi/strxfrm',
'ansi/calloc',
'ansi/fgetpos',
'ansi/fputs',
'ansi/ftell',
'bsd/ns_get_put',
'bsd/reallocarray',
Expand Down

0 comments on commit 1e4c032

Please sign in to comment.