gpt4 book ai didi

rust - 在读取文件时配置换行符

转载 作者:行者123 更新时间:2023-12-03 11:44:27 25 4
gpt4 key购买 nike

我是 rust 编程的新手,正尝试逐行读取文件。看起来好像它最后删除了换行符,并且仅返回了文本。
我正在读取具有\n和\r\n的元数据文件。
文件示例在下面我明确添加\n和\r\n的位置。

TAG 0\n
15:\n
32348SIPpTag091\n

SDP from 0 after offer
215:
v=0\r\n
o=user1 53655765 2353687637 IN IP4 172.31.8.95\r\n
s=-\r\n
c=IN IP4 172.31.8.95\r\n
t=0 0\r\n
m=audio 34218 RTP/AVP 8\r\n
c=IN IP4 172.31.8.95\r\n
a=direction:both\r\n
a=label:a_leg\r\n
a=rtpmap:8 PCMA/8000\r\n
a=sendonly\r\n
a=rtcp:34219\r\n
我正在 map 中捕获此信息,其中 TAG 0是我的键,而 32348SIPpTag091是值,而这行 15:提供了值的长度。基于此长度,我正在确定是否已收到该值。
但是使用下面的代码,我将\r和\n一起丢失,因此长度与内容不匹配。
在rust中,有什么方法可以配置为只寻找\n作为换行符,还是不从行中删除那些字符。
这是我的代码
fn read_meta(path: &str) -> MetaInfo {
let mut map = HashMap::new();
let mut idx: String = String::from("");
let mut data: String = String::from("");
let mut dlen: i32 = -1;

println!("reading from {}", path);
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line.unwrap();
if idx.is_empty() {
if line.len() <= 1 {
continue;
}
idx = String::from(line.trim_end_matches("\n"));
} else if dlen == -1 {
let c = String::from(line.trim_end_matches("\n").trim_end_matches(":"));
dlen = c.parse::<i32>().unwrap();
} else {
data = data + &line;
if data.len() as i32 >= dlen {
let diff = (data.len() as i32 - dlen) * -1;
if diff < 0 {
let val = data.chars().take(dlen as usize).collect();
map.insert(idx.to_string(), val);
} else {
map.insert(idx.to_string(), data);
}
idx = String::from("");
dlen = -1;
data = String::from("");
}
}
}
let meta_info = MetaInfo {
index: String::from(map.get("PARENT").unwrap()),
is_complete: map.contains_key("PARENT") && map.contains_key("SDP from 1 after answer")
};
return meta_info;

}

最佳答案

如您所见,lines实用程序将去除结尾的换行符(仅CR LF或LF),以方便使用。这是不可配置的
如果您不希望这种行为,则可以使用较低级别的 read_line :它将读取一行并将其放入您提供的包含EOL内容的缓冲区中,无论是单独的LF还是CR LF。虽然这不是一个可迭代的过程,所以您必须手动处理它,例如:

let mut buf = String::new();
while let Ok(n) = reader.read_line(&mut buf) {
if n == 0 { break; } // eof

// do stuff with `buf` string here

buf.clear(); // otherwise the data will accumulate in your buffer
}
playground demo

关于rust - 在读取文件时配置换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64661527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com