pub unsafe fn read(fd: i32, buf: &mut [u8]) -> Result<ssize_t, Errno>
Expand description
Read from a file descriptor.
§Examples
let path = "/etc/passwd";
let ret = unsafe { nc::openat(nc::AT_FDCWD, path, nc::O_RDONLY, 0) };
assert!(ret.is_ok());
let fd = ret.unwrap();
let mut buf = [0_u8; 4 * 1024];
let ret = unsafe { nc::read(fd, &mut buf) };
assert!(ret.is_ok());
let n_read = ret.unwrap();
assert!(n_read <= buf.len() as nc::ssize_t);
let ret = unsafe { nc::close(fd) };
assert!(ret.is_ok());
Examples found in repository?
More examples
examples/read.rs (line 14)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
fn main() -> Result<(), nc::Errno> {
#[cfg(any(target_os = "linux", target_os = "android"))]
let fd = unsafe { nc::openat(nc::AT_FDCWD, "/etc/passwd", nc::O_RDONLY, 0)? };
#[cfg(target_os = "freebsd")]
let fd = unsafe { nc::open("/etc/passwd", nc::O_RDONLY, 0)? };
let mut buf: [u8; 256] = [0; 256];
loop {
let n_read = unsafe { nc::read(fd, &mut buf) };
match n_read {
Ok(n) => {
if n == 0 {
break;
}
// FIXME(Shaohua): Read buf with len(n).
if let Ok(s) = std::str::from_utf8(&buf) {
print!("s: {}", s);
} else {
eprintln!("Failed to read buf as UTF-8!");
break;
}
}
Err(errno) => {
eprintln!("Failed to read, got errno: {}", errno);
break;
}
}
}
unsafe { nc::close(fd) }
}