Skip to main content

read/
read.rs

1// Copyright (c) 2020 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5fn main() -> Result<(), nc::Errno> {
6    #[cfg(any(target_os = "linux", target_os = "android"))]
7    let fd = unsafe { nc::openat(nc::AT_FDCWD, "/etc/passwd", nc::O_RDONLY, 0)? };
8
9    #[cfg(target_os = "freebsd")]
10    let fd = unsafe { nc::open("/etc/passwd", nc::O_RDONLY, 0)? };
11
12    let mut buf: [u8; 256] = [0; 256];
13    loop {
14        let n_read = unsafe { nc::read(fd, &mut buf) };
15        match n_read {
16            Ok(n) => {
17                if n == 0 {
18                    break;
19                }
20                // FIXME(Shaohua): Read buf with len(n).
21                if let Ok(s) = std::str::from_utf8(&buf) {
22                    print!("s: {}", s);
23                } else {
24                    eprintln!("Failed to read buf as UTF-8!");
25                    break;
26                }
27            }
28            Err(errno) => {
29                eprintln!("Failed to read, got errno: {}", errno);
30                break;
31            }
32        }
33    }
34
35    unsafe { nc::close(fd) }
36}