How to get the size of an already-opened File in Rust?
The std::fs::File
provides a metadata
method. It can be used with your my_file
like this:
my_file.metadata().unwrap().len();
There are a few options.
If you create the file like you did (
File::create
), you will truncate the file, which means it will set the size of that file to0
and write the content ofbuffer
to the file. This means that your file will now have the lengthbuffer.len()
.Use
File::metadata
to get the metadata and therefore get the length of the file. Keep in mind that you have to sync the file (by usingFile::sync_all
) with the underlying filesystem to update the metadata and get the correct value.Use
Seek::seek
whichFile
implements. You can then get the current offset by usingmy_file.seek(SeekFrom::End(0))
which will tell you the last position available.On nightly (expected for release 1.35.0), you can use
Seek::stream_len
, which, unlikeseek(SeekFrom::End(0))
, restores the previous seek position.