Skip to content

stdin().read(&mut [u8]) reads insufficient data #84284

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
bczhc opened this issue Apr 18, 2021 · 2 comments
Closed

stdin().read(&mut [u8]) reads insufficient data #84284

bczhc opened this issue Apr 18, 2021 · 2 comments

Comments

@bczhc
Copy link

bczhc commented Apr 18, 2021

I have a file with enough size to read, but when I use stdin().read(...), I found the read size it returned has wrong result.

Code:

fn main() {
    let mut f = stdin();
    let mut buf: [u8; 3] = [0, 0, 0];
    let mut c = 0;
    loop {
        let i = f.read(&mut buf).unwrap();
        if i == 0 { break; }
        println!("{} {}", i, c);
        c += 1;
    }   
}

Command: cat some-file | ./main

The output will look like this:

3 1

3 2

3 3

... Omit a lot of 3s

3 2729

2 2730 // here: it reads only two bytes but not the expected 3

3 2731

3 2731

...

2 5461 // same here

3

3

...

Command: cat some-file | ./main | grep "2 "
Output:

2 2730

2 5461

2 8192

2 10923

2 13654

2 16385

2 19116

2 21847

2 24578

2 27309

2 30040

...

I don't know whether it's a bug or there is another right way to read bytes from stdin so that the case above can be avoided.

Rustc version: 1.51.0

@jonas-schievink
Copy link
Contributor

read is allowed to return smaller values than the buffer you passed in, even if more data could be read. Use read_exact if you need your buffer to be filled completely.

@bczhc
Copy link
Author

bczhc commented Apr 18, 2021

Thanks it works!
Also when using stdin(), there's a memory leak, as #80406...

@bczhc bczhc closed this as completed Apr 18, 2021
@bczhc bczhc changed the title stdin().read(&mut [u8]) reads inefficient data stdin().read(&mut [u8]) reads sufficient data Apr 18, 2021
@bczhc bczhc changed the title stdin().read(&mut [u8]) reads sufficient data stdin().read(&mut [u8]) reads insufficient data Apr 18, 2021
@bczhc bczhc changed the title stdin().read(&mut [u8]) reads insufficient data stdin().read(&mut [u8]) reads insufficient data Apr 19, 2021
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants