-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
scanf
behaviour is strange
#6505
Comments
I am surprised this works at all - we don't seem to have any special code to handle (I'm also unsure about the bash differences between pipes and redirection, I would have guessed both work as pipes internally...) |
This issue has been automatically marked as stale because there has been no activity in the past year. It will be closed automatically if no further activity occurs in the next 7 days. Feel free to re-open at any time if this issue is still relevant. |
The problem still exists in current version. emcc (Emscripten gcc/clang-like replacement) 1.38.45 (commit 252410a) |
Underlying code seems to use |
I can repro with this extracted bit on node: var fs = require('fs');
function get_chars() {
// we will read data by chunks of BUFSIZE
var BUFSIZE = 256;
var buf = Buffer.alloc ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE);
var bytesRead = 0;
var isPosixPlatform = (process.platform != 'win32'); // Node doesn't offer a direct check, so test by exclusion
var fd = process.stdin.fd;
if (isPosixPlatform) {
// Linux and Mac cannot use process.stdin.fd (which isn't set up as sync)
var usingDevice = false;
try {
fd = fs.openSync('/dev/stdin', 'r');
usingDevice = true;
} catch (e) {}
}
try {
bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null);
} catch(e) {
// Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
// reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
if (e.toString().indexOf('EOF') != -1) bytesRead = 0;
else throw e;
}
if (usingDevice) { fs.closeSync(fd); }
if (bytesRead > 0) {
result = buf.slice(0, bytesRead).toString('utf-8');
} else {
result = null;
}
return result;
}
for (var i = 0; i < 2; i++) {
let s = get_chars();
console.log({s});
} Second get_chars() call buffers up the beginning of input again instead of the second chunk as expected, but only when using file redirection and not when using a pipe. |
I get the same 'restarting' behavior with a C program on Linux, so I think the code is just not using |
If i remove the isPosixPlatform this seems to work as expected.. so perhaps we can simply remove that workaround? |
scanf
behaviour is strange.main.cpp: read at most 200 numbers and print them.
Input (
in.txt
):Compile with default options:
Output is incorrect when using bash redirection:
Output is correct when using pipe:
My environment:
The text was updated successfully, but these errors were encountered: