Problems with File::set_len() function

I have been learning File documentation and testing different functions and I am having a problem with set_len() function:

My code:

let mut f = File::create("foo.txt")?;

f.set_len(3)?;

The text in the file after compiling the code: three rombes with the question marks.

Is there a way to fix that, so that the file contains utf-8 values?

The file is filled with null bytes. Those are valid utf-8.

If you want it to contain something else, you should write those contents to the file.

5 Likes

May be I don't understand something, but this happens even if the file len is bigger than size the function takes.
For example, if the file data is "abcdd", and I set its len to 3, the file data looks like that: ���

File::create() overwrites any existing file with an empty one. So even if you had a file with something in it, you always start over with an empty file. You want to open the file for writing, but not for overwriting.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.