@@ -662,24 +662,28 @@ static int io_readline (lua_State *L) {
662662
663663static int g_write (lua_State * L , FILE * f , int arg ) {
664664 int nargs = lua_gettop (L ) - arg ;
665- int status = 1 ;
665+ size_t totalbytes = 0 ; /* total number of bytes written */
666666 errno = 0 ;
667- for (; nargs -- ; arg ++ ) {
667+ for (; nargs -- ; arg ++ ) { /* for each argument */
668668 char buff [LUA_N2SBUFFSZ ];
669669 const char * s ;
670+ size_t numbytes ; /* bytes written in one call to 'fwrite' */
670671 size_t len = lua_numbertocstring (L , arg , buff ); /* try as a number */
671672 if (len > 0 ) { /* did conversion work (value was a number)? */
672673 s = buff ;
673674 len -- ;
674675 }
675676 else /* must be a string */
676677 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+ }
678685 }
679- if (l_likely (status ))
680- return 1 ; /* file handle already on stack top */
681- else
682- return luaL_fileresult (L , status , NULL );
686+ return 1 ; /* no errors; file handle already on stack top */
683687}
684688
685689
0 commit comments