Skip to main content

dir/
dir.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
5use std::env;
6
7fn main() {
8    const BUF_SIZE: usize = 1024;
9
10    let path = env::args().nth(1).unwrap_or_else(|| ".".to_owned());
11    let ret = unsafe { nc::openat(nc::AT_FDCWD, path, nc::O_DIRECTORY, 0) };
12    assert!(ret.is_ok());
13    let fd = ret.unwrap();
14    let mut buf = [0; BUF_SIZE];
15
16    loop {
17        let ret = unsafe { nc::getdents64(fd, &mut buf) };
18        assert!(ret.is_ok());
19        let nread = ret.unwrap() as usize;
20        if nread == 0 {
21            break;
22        }
23
24        let buf_ptr: *const u8 = buf.as_ptr();
25        let mut bpos: usize = 0;
26
27        println!("--------------- nread={nread} ---------------");
28        println!("inode#    file type  d_reclen  d_off   d_name");
29        while bpos < nread {
30            let d = buf_ptr.wrapping_add(bpos) as *mut nc::linux_dirent64_t;
31            let d_ref: &nc::linux_dirent64_t = unsafe { &(*d) };
32            let d_type = match d_ref.d_type {
33                nc::DT_REG => "regular",
34                nc::DT_DIR => "directory",
35                nc::DT_FIFO => "FIFO",
36                nc::DT_SOCK => "socket",
37                nc::DT_LNK => "symlink",
38                nc::DT_BLK => "block-dev",
39                nc::DT_CHR => "char-dev",
40                nc::DT_UNKNOWN => "dt unknown",
41                _ => "other unknown",
42            };
43
44            if let Ok(name) = std::str::from_utf8(d_ref.name()) {
45                println!(
46                    "{: >8}  {:<10} {: >4} {: >12}  {}",
47                    d_ref.d_ino, d_type, d_ref.d_reclen, d_ref.d_off as u32, name
48                );
49            } else {
50                eprintln!("Invalid name: {:?}", d_ref.name());
51            }
52
53            bpos += d_ref.d_reclen as usize;
54        }
55    }
56
57    //    println!(
58    //        "offset of d_name is: {}",
59    //        offset_of!(nc::linux_dirent_t, d_name)
60    //    );
61    //    println!(
62    //        "offset of d_reclen is: {}",
63    //        offset_of!(nc::linux_dirent_t, d_reclen)
64    //    );
65
66    let ret = unsafe { nc::close(fd) };
67    assert!(ret.is_ok());
68}