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

  • 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.

主站蜘蛛池模板: 从江县| 徐闻县| 商丘市| 抚松县| 东山县| 桦南县| 凤城市| 巴林右旗| 平陆县| 宜君县| 赤壁市| 闽清县| 垣曲县| 南宫市| 财经| 岢岚县| 普陀区| 托克逊县| 丽江市| 武城县| 赞皇县| 墨竹工卡县| 房产| 灵武市| 贵港市| 咸阳市| 沁水县| 连江县| 毕节市| 乐清市| 独山县| 女性| 双辽市| 分宜县| 于都县| 邵东县| 石泉县| 奇台县| 保亭| 东乌珠穆沁旗| 正镶白旗|