我正在尝试使用同一std::fs::File对象进行写入和读取,但是读取返回一个空字符串。
我想flush,sync_all和seek,但没有任何帮助。使用新File对象,我可以轻松读取文件。
use std::io::{Read, Seek, Write};
const FILE_PATH: &str = "test.txt";
fn main() {
// Create file
let mut f = std::fs::File::create(FILE_PATH).unwrap();
f.write_all("foo bar".as_bytes());
f.seek(std::io::SeekFrom::Start(0));
// Read from the same descriptor
let mut content = String::new();
f.read_to_string(&mut content);
println!("{:?}", content); // -> ""
// Read from the other descriptor
let mut f = std::fs::File::open(FILE_PATH).unwrap();
let mut content = String::new();
f.read_to_string(&mut content);
println!("{:?}", content); // -> "foo bar"
}
Run Code Online (Sandbox Code Playgroud)
问题出在File::create—它以只写模式打开文件。解决方法是使用std::fs::OpenOptions:
let mut f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.read(true)
.open(FILE_PATH)
.unwrap();
Run Code Online (Sandbox Code Playgroud)
别忘了用重置阅读位置seek。
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |