diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2025-04-03 11:32:49 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2025-04-03 11:32:49 -0300 |
commit | 3f4f28010aa5065456f1edf97de1ab268cc49944 (patch) | |
tree | 18ef631f33d1e71cf7f9d20b67d9148499a9dcf4 /liolib.c | |
parent | 93e347b51923a3f0b993aac37c74e1489c02f3b5 (diff) | |
download | lua-3f4f28010aa5065456f1edf97de1ab268cc49944.tar.gz lua-3f4f28010aa5065456f1edf97de1ab268cc49944.tar.bz2 lua-3f4f28010aa5065456f1edf97de1ab268cc49944.zip |
io.write returns number of written bytes on error
Diffstat (limited to 'liolib.c')
-rw-r--r-- | liolib.c | 18 |
1 files changed, 11 insertions, 7 deletions
@@ -662,11 +662,12 @@ static int io_readline (lua_State *L) { | |||
662 | 662 | ||
663 | static int g_write (lua_State *L, FILE *f, int arg) { | 663 | static int g_write (lua_State *L, FILE *f, int arg) { |
664 | int nargs = lua_gettop(L) - arg; | 664 | int nargs = lua_gettop(L) - arg; |
665 | int status = 1; | 665 | size_t totalbytes = 0; /* total number of bytes written */ |
666 | errno = 0; | 666 | errno = 0; |
667 | for (; nargs--; arg++) { | 667 | for (; nargs--; arg++) { /* for each argument */ |
668 | char buff[LUA_N2SBUFFSZ]; | 668 | char buff[LUA_N2SBUFFSZ]; |
669 | const char *s; | 669 | const char *s; |
670 | size_t numbytes; /* bytes written in one call to 'fwrite' */ | ||
670 | size_t len = lua_numbertocstring(L, arg, buff); /* try as a number */ | 671 | size_t len = lua_numbertocstring(L, arg, buff); /* try as a number */ |
671 | if (len > 0) { /* did conversion work (value was a number)? */ | 672 | if (len > 0) { /* did conversion work (value was a number)? */ |
672 | s = buff; | 673 | s = buff; |
@@ -674,12 +675,15 @@ static int g_write (lua_State *L, FILE *f, int arg) { | |||
674 | } | 675 | } |
675 | else /* must be a string */ | 676 | else /* must be a string */ |
676 | s = luaL_checklstring(L, arg, &len); | 677 | s = luaL_checklstring(L, arg, &len); |
677 | status = status && (fwrite(s, sizeof(char), len, f) == len); | 678 | numbytes = fwrite(s, sizeof(char), len, f); |
679 | totalbytes += numbytes; | ||
680 | if (numbytes < len) { /* write error? */ | ||
681 | int n = luaL_fileresult(L, 0, NULL); | ||
682 | lua_pushinteger(L, cast_st2S(totalbytes)); | ||
683 | return n + 1; /* return fail, error msg., error code, and counter */ | ||
684 | } | ||
678 | } | 685 | } |
679 | if (l_likely(status)) | 686 | return 1; /* no errors; file handle already on stack top */ |
680 | return 1; /* file handle already on stack top */ | ||
681 | else | ||
682 | return luaL_fileresult(L, status, NULL); | ||
683 | } | 687 | } |
684 | 688 | ||
685 | 689 | ||