'How to read the first N bytes of a file or less if it is shorter? [duplicate]

Is there an easy way to read the first N bytes of a file in Rust? The two most relevant functions seem to be read and read_exact, but read can return fewer bytes than available for whatever reason, so I would have to call it in an annoying loop, and read_exact gives up if the file is shorter than N bytes (whereas I'd prefer it to just read the entire file).

This is not a duplicate of this question which can be solved with read_exact: How to read a specific number of bytes from a stream?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source