How can I get the size/length of the file that is declared as a File
variable?
There is an option for getting it using the file name via fs::metadata
:
let x = fs::metadata(file_path)?.len();
But I have a file that I already created and edited:
let mut my_file = File::create(file_path).unwrap();
my_file.write_all(buffer) // buffer is a data which comes from network and put into Vec<u8>
// From here, does it possible to get my_file length?
// Looking something like my_file.len();
Are there any function that gives the length of the File
?
Write to a FileThe create() method is used to create a file. The method returns a file handle if the file is created successfully. The last line write_all function will write bytes in newly created file. If any of the operations fail, the expect() function returns an error message.
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 to 0
and write the content of buffer
to the file. This means that your file will now have the length buffer.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 using File::sync_all
) with the underlying filesystem to update the metadata and get the correct value.
Use Seek::seek
which File
implements. You can then get the current offset by using my_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, unlike seek(SeekFrom::End(0))
, restores the previous seek position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With