- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 243字
- 2021-07-02 23:07:22
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.
- Mastering Entity Framework Core 2.0
- Raspberry Pi for Secret Agents(Third Edition)
- 基于Java技術的Web應用開發(fā)
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務、多團隊協(xié)同等核心場景實戰(zhàn)
- 零基礎學Python網(wǎng)絡爬蟲案例實戰(zhàn)全流程詳解(高級進階篇)
- H5頁面設計:Mugeda版(微課版)
- Spring Boot企業(yè)級項目開發(fā)實戰(zhàn)
- C++新經(jīng)典
- Python項目實戰(zhàn)從入門到精通
- 新印象:解構(gòu)UI界面設計
- OpenCV Android開發(fā)實戰(zhàn)
- 深入大型數(shù)據(jù)集:并行與分布化Python代碼
- Visual C++網(wǎng)絡編程教程(Visual Studio 2010平臺)
- 面向?qū)ο蟪绦蛟O計教程(C#版)
- 你也能看得懂的Python算法書