diff options
-rw-r--r-- | src/library.js | 19 | ||||
-rwxr-xr-x | tests/runner.py | 16 |
2 files changed, 33 insertions, 2 deletions
diff --git a/src/library.js b/src/library.js index 9a1f29e5..f7c7a3ba 100644 --- a/src/library.js +++ b/src/library.js @@ -3660,8 +3660,23 @@ LibraryManager.library = { // http://pubs.opengroup.org/onlinepubs/000095399/functions/scanf.html if (FS.streams[stream]) { var i = _ftell(stream), SEEK_SET = 0; - var get = function () { i++; return _fgetc(stream); }; - var unget = function () { _fseek(stream, --i, SEEK_SET); }; + // if the stream does not support seeking backwards (e.g. stdin), buffer it here + var buffer = [], bufferIndex = 0; + 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--; + } + }; return __scanString(format, get, unget, varargs); } else { return -1; diff --git a/tests/runner.py b/tests/runner.py index effdfb20..77f36cf5 100755 --- a/tests/runner.py +++ b/tests/runner.py @@ -11227,6 +11227,22 @@ f.close() self.assertContained('libf1\nlibf2\n', run_js(os.path.join(self.get_dir(), 'a.out.js'))) + def test_stdin(self): + open('main.cpp', 'w').write(r''' +#include <stdio.h> +int main(int argc, char const *argv[]) +{ + char str[10] = {0}; + scanf("%10s", str); + printf("%s\n", str); + return 0; +} +''') + Building.emcc('main.cpp', output_filename='a.out.js') + open('in.txt', 'w').write('abc') + # 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_abspaths(self): # Includes with absolute paths are generally dangerous, things like -I/usr/.. will get to system local headers, not our portable ones. |