官术网_书友最值得收藏!

Writing a file

Writing to a file is a two-step process: opening the file (possibly creating it if it didn't exist before) and then the writing of the file. This is very similar to how writing to a file in the C family of languages is carried out.

You can create a file for writing in a single call to std::fs::File::create. The open method in the same namespace opens a file for reading. If you need more fine-tuned permissions, std::fs::OpenOptions::new creates an object through which you can tweak the parameters and then open the file.

As with any file operation, anything could fail, so the result should always be checked:

let file: Result<File,Error> = options.open(path); 
 

As mentioned before, Rust uses a generic type, Result<T,U> , quite frequently as an error-trapping mechanism. It encapsulates two values: the left-hand side value is used when the operation succeeds, and the right-hand side value is used when it does not succeed.

Once we have completed the file creation, we can move on to writing to the file.

First, we check the results of the Result comparison. If an error hasn't been thrown there was no error, and we can then create a BufWriter:

let mut writer = BufWriter::new(&file); 
writer.write_all(b"hello text file\n"); 

We don't need to flush the buffer, as write_all will do that for us (it calls flush() once completed). If you don't use write_all, then you need to call flush() to ensure the buffer is cleared.

主站蜘蛛池模板: 织金县| 珲春市| 湟源县| 宜兰县| 岳阳市| 淮北市| 华宁县| 海城市| 工布江达县| 古丈县| 房产| 册亨县| 二手房| 合肥市| 永登县| 宝应县| 仙桃市| 罗城| 寿光市| 邵东县| 从江县| 威远县| 阿图什市| 宜兴市| 阿鲁科尔沁旗| 中江县| 甘德县| 洛扎县| 巧家县| 鄯善县| 陕西省| 临澧县| 黎城县| 翼城县| 汶川县| 睢宁县| 西盟| 白玉县| 西平县| 莱西市| 抚宁县|