Now that I know I can read a single group, the next step is to iterate.
Iteration of this C API requires the ability to test for the end of iteration. For this, I use the std::ptr to test for a null pointer. To include this in the rust file:
use std::ptr; |
To test for the a null pointer in a while loop:
while groupent != ptr::null(){This style of while loop requires calling the getgrpent function twice. I don’t love that, but it seems to be the clearest code. here is the whole loop:
fn enumerate_groups(){ let mut groupent: * const GroupEnt; unsafe{ setgrent(); groupent = getgrent(); } while groupent != ptr::null(){ let c_str: &CStr = unsafe { CStr::from_ptr((*groupent).gr_name) }; println!("{}", c_str.to_str().unwrap()); unsafe{ groupent = getgrent(); } } unsafe{ endgrent(); } } |
The multiple unsafe blocks are to try an isolate the unsafe portions, but also to enable refactoring as a follow on step.