It does this by using the read_to_string function in the fs module, which takes the file’s path value as an argument. In addition, we have to specify what happens if, for any reason, the file can’t open; for example, if there’s a permission error or something similar. The code...
1、逐行读文本 use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; fn main() { // File hosts must exist in current path before this produces output if let Ok(lines) = read_lines("./hosts") { // Consumes the iterator, returns an (Optional) String for line...
Ok(io::BufReader::new(file).lines()) } 2 一次读入文本 use std::fs::File; use std::io::prelude::*; use std::path::Path; fn main() {//Create a path to the desired myfilelet path = Path::new("a.txt"); let display=path.display();//Open the path in read-only mode, ret...
usestd::fs::File;usestd::io::Read;fnmain(){letmutinfo=String::new();letmutf=File::open("/etc/hosts").expect("The file cannot be opened");f.read_to_string(&mutdata).expect("The string cannot be read");println!("{}",info);} mut关键字是指可变的,File::open打开路径/etc/hosts...
file.write_all(b"sourceforge.net\n")?; Rust 文件读取 适用于写的东西也适用于读。读取也可以通过简单的一行代码来完成: let websites=fs::read_to_string("favorite_websites.txt")?; 以上一行读取文件的内容并返回一个字符串。除了读取字符串,还有 std::fs::read 🔗 doc.rust-lang.org 函数,如果文...
; let input = File::open(path)?; let buffered = BufReader::new(input); for words in buffered.lines() { println!("{}", words?); } Ok(()) } 在上面的代码中,File::create 打开一个文件用于写入,File::open 用于读取。BufRead 有一个内部缓冲区来读取文件,并且对于逐行读取更有用。 缓冲...
文件创建成功:File { fd: 3, path: "/Users/Admin/Downloads/guess-game-app/src/data.txt", read: false, write: true } 24.3 Rust 写入文件 Rust 语言标准库 std::io::Writes 提供了函数 write_all() 用于向输出流写入内容。 因为文件流也是输出流的一种,所以该函数也可以用于向文件写入内容。
use std::io::{self, Read}; fn read_file_contents(filename: &str) -> io::Result<String> { let mut file = File::open(filename)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) }
std::fs::File::open usestd::error::Error;usestd::fs::File;usestd::io::prelude::*;usestd::path::Path;fnmain(){// Create a path to the desired fileletpath=Path::new("hello.txt");letdisplay=path.display();// Open the path in read-only mode, returns `io::Result<File>`letmut...
We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Cancel Submit feedback Saved searches Use saved searches to filter your results more quickly Cancel Create saved search Sign in Sign up Reseting focus {...