本文介绍了是否可以使用同一个文件进行读写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用相同的 std::fs::File
对象进行写入和读取,但读取返回空字符串.
I'm trying to use the same std::fs::File
object for writing and reading, but reading returns an empty string.
我尝试了 flush
、sync_all
和 seek
,但没有任何帮助.使用新的 File
对象,我可以轻松读取文件.
I tried to flush
, sync_all
and seek
, but nothing helped. With a new File
object I can read the file easily.
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"
}
推荐答案
问题出在 File::create
— 它 以只写模式打开文件.修复方法是使用 std::fs::OpenOptions
:
The problem was with File::create
— it opens a file in write-only mode. The fix is to use std::fs::OpenOptions
:
let mut f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.read(true)
.open(FILE_PATH)
.unwrap();
不要忘记用seek
重置阅读位置.
Don't forget to reset the reading position with seek
.
这篇关于是否可以使用同一个文件进行读写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!