diff options
-rw-r--r-- | src/library.js | 16 | ||||
-rwxr-xr-x | tests/runner.py | 23 |
2 files changed, 26 insertions, 13 deletions
diff --git a/src/library.js b/src/library.js index 59f2f6c6..893bd32a 100644 --- a/src/library.js +++ b/src/library.js @@ -3653,29 +3653,19 @@ LibraryManager.library = { ___setErrNo(ERRNO_CODES.EAGAIN); return -1; }, - fscanf__deps: ['$FS', '__setErrNo', '$ERRNO_CODES', - '_scanString', 'fgetc', 'fseek', 'ftell'], + fscanf__deps: ['$FS', '_scanString', 'fgetc', 'ungetc'], fscanf: function(stream, format, varargs) { // int fscanf(FILE *restrict stream, const char *restrict format, ... ); // http://pubs.opengroup.org/onlinepubs/000095399/functions/scanf.html if (FS.streams[stream]) { - var i = _ftell(stream), SEEK_SET = 0; - // if the stream does not support seeking backwards (e.g. stdin), buffer it here - var buffer = [], bufferIndex = 0; + var buffer = []; var get = function() { - if (bufferIndex < buffer.length) { - return buffer[bufferIndex++]; - } - i++; - bufferIndex++; var c = _fgetc(stream); buffer.push(c); return c; }; var unget = function() { - if (_fseek(stream, --i, SEEK_SET) !== 0) { - bufferIndex--; - } + _ungetc(buffer.pop(), stream); }; return __scanString(format, get, unget, varargs); } else { diff --git a/tests/runner.py b/tests/runner.py index 1948ab59..c813a921 100755 --- a/tests/runner.py +++ b/tests/runner.py @@ -11246,6 +11246,29 @@ int main(int argc, char const *argv[]) # node's stdin support is broken self.assertContained('abc', Popen(listify(SPIDERMONKEY_ENGINE) + ['a.out.js'], stdin=open('in.txt'), stdout=PIPE, stderr=PIPE).communicate()[0]) + def test_ungetc_fscanf(self): + open('main.cpp', 'w').write(r''' + #include <stdio.h> + int main(int argc, char const *argv[]) + { + char str[4] = {0}; + FILE* f = fopen("my_test.input", "r"); + if (f == NULL) { + printf("cannot open file\n"); + return -1; + } + ungetc('x', f); + ungetc('y', f); + ungetc('z', f); + fscanf(f, "%3s", str); + printf("%s\n", str); + return 0; + } + ''') + open('my_test.input', 'w').write('abc') + Building.emcc('main.cpp', ['--embed-file', 'my_test.input'], output_filename='a.out.js') + self.assertContained('zyx', Popen(listify(JS_ENGINES[0]) + ['a.out.js'], stdout=PIPE, stderr=PIPE).communicate()[0]) + def test_abspaths(self): # Includes with absolute paths are generally dangerous, things like -I/usr/.. will get to system local headers, not our portable ones. |