Sub topic 15
OsString, Path, and CString
This chapter assumes you know the &str and String split from earlier chapters and that str is always valid UTF-8. It also assumes you are comfortable with Option, Result, and borrowing. Here you will learn why String is the wrong type for file names, environment variables, and C interop, and which type to use in each case.
Why String is not always enough
String guarantees valid UTF-8. The outside world does not make that promise.
- A Linux file name is any sequence of bytes except
/and the NUL byte (a zero byte). It does not have to be UTF-8. - A Windows file name is a sequence of 16-bit units (UTF-16) that may contain unpaired surrogates. Those cannot be converted to valid UTF-8.
- A C string is a run of bytes that ends at the first zero byte. It may hold any bytes before that, and it may not hold a zero byte inside.
Rust has one string type for each of these situations. Each one gives up a guarantee that String has, so that it can represent data String cannot.
| Owned | Borrowed | Holds | Typical use |
|---|---|---|---|
| `String` | `&str` | Valid UTF-8 | Text your program controls |
| `OsString` | `&OsStr` | Platform-native text, possibly not UTF-8 | Environment variables, arguments, file names |
| `PathBuf` | `&Path` | An `OsString` with path methods | File system paths |
| `CString` | `&CStr` | Bytes with one trailing NUL and no interior NUL | Calling C APIs |
The owned and borrowed types follow the same pattern as String and &str. The owned type allocates and can grow. The borrowed type is a view, and &OsStr, &Path and &CStr are all unsized slice-like types you normally see behind a reference.
OsString and OsStr
OsString and OsStr hold text in the form the operating system uses. On Unix that is arbitrary bytes. On Windows it is a superset of UTF-16 called WTF-8 internally. You do not see that encoding. You only see that the conversion to str can fail.
The standard library returns OsString wherever the OS controls the data:
std::env::args_os()andstd::env::var_os()give arguments and environment variables.DirEntry::file_name()gives the name of a directory entry.Path::file_name()andPath::extension()give&OsStr.
Two conversions matter most.
to_str()returnsOption<&str>. It isNoneif the data is not valid UTF-8.to_string_lossy()returnsCow<str>. It replaces invalid sequences with the replacement characterU+FFFDand borrows when nothing needed replacing. This is the sameCowidea from the previous chapter.
The next program is Unix-only because it builds a non-UTF-8 name from raw bytes. That ability comes from the OsStrExt extension trait, which exists only on Unix.
#[cfg(unix)]
fn main() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let name = OsStr::from_bytes(b"caf\xe9.txt");
println!("{:?}", name.to_str());
println!("{}", name.to_string_lossy());
}
#[cfg(not(unix))]
fn main() {
println!("This example needs a Unix platform.");
}The byte 0xE9 is é in Latin-1 but is not valid UTF-8 on its own. to_str() prints None, and to_string_lossy() prints caf�.txt.
You can build an OsString from a String or &str with OsString::from or .into(). That direction always works, because every UTF-8 string is valid for the OS. The reverse direction needs into_string(), which returns Result<String, OsString>. On failure you get your original value back inside Err, so nothing is lost.
OsStr has very few methods compared with str. You cannot slice it, split it, or search it. That is deliberate. Operations like "find the character x" have no single meaning across platform encodings. If you need real text processing, convert to str first and decide what to do when conversion fails.
Path and PathBuf
Path is to PathBuf what str is to String. A Path wraps an OsStr and adds methods that understand separators, file names, and extensions. PathBuf owns its data and can be changed.
use std::path::{Path, PathBuf};
fn main() {
let mut p = PathBuf::from("/tmp");
p.push("reports");
p.push("2026.txt");
println!("{}", p.display());
println!("{:?}", p.file_name());
println!("{:?}", p.extension());
let parent: Option<&Path> = p.parent();
println!("{:?}", parent);
p.set_extension("csv");
println!("{}", p.display());
}On Unix this prints /tmp/reports/2026.txt, Some("2026.txt"), Some("txt"), Some("/tmp/reports"), and /tmp/reports/2026.csv.
Note these details:
Path::new("x")borrows from a&strwithout allocating. It accepts anything that implementsAsRef<OsStr>, which includes&str,String,OsStr, andPathBuf.display()returns a helper that implementsDisplay.Pathitself does not implementDisplay, because a path may not be printable as text.display()uses lossy conversion internally.pushandjoinuse the platform separator. Do not build paths by concatenating strings with/or\\.
The join gotcha
join and push replace the whole path when the argument is absolute.
use std::path::Path;
fn main() {
let base = Path::new("/srv/app");
println!("{}", base.join("logs").display());
println!("{}", base.join("/etc/passwd").display());
}The output is /srv/app/logs and then /etc/passwd. If the second part comes from user input, this lets the user escape your base directory. Check is_absolute() on untrusted parts, and reject any .. components, which you can find with components(). Neither check on its own is a full defense against path traversal, because symbolic links can still lead outside the base. Canonicalize the result with std::fs::canonicalize and compare it to the canonicalized base when security matters.
Accepting paths in function signatures
Use the same idea as &str in function signatures. Take &Path for a plain borrow. Take impl AsRef<Path> when you want callers to pass a &str, String, PathBuf, or &Path without conversions. This is what std::fs::read_to_string does.
use std::fs;
use std::path::Path;
fn line_count(path: impl AsRef<Path>) -> std::io::Result<usize> {
let text = fs::read_to_string(path.as_ref())?;
Ok(text.lines().count())
}
fn main() {
match line_count("Cargo.toml") {
Ok(n) => println!("{n} lines"),
Err(e) => println!("could not read file: {e}"),
}
}The result depends on whether Cargo.toml exists in the working directory. The error branch is normal behavior, not a bug.
Listing files without losing names
When you read a directory, file_name() returns an OsString. Handle the non-UTF-8 case on purpose.
use std::env;
use std::fs;
fn main() -> std::io::Result<()> {
let dir = env::current_dir()?;
for entry in fs::read_dir(&dir)? {
let name = entry?.file_name();
match name.to_str() {
Some(s) => println!("ok: {s}"),
None => println!("skip: {}", name.to_string_lossy()),
}
}
Ok(())
}Calling name.to_str().unwrap() here would crash on the first oddly named file. A program that reads untrusted directories should either skip such names, as above, or keep working with the OsString and never convert at all.
CString and CStr
C strings end at the first zero byte, so they cannot contain one inside. Rust strings have the opposite rule: they may contain \0 anywhere and are not terminated. CString bridges the two.
CString::new(...)copies the bytes, checks that there is no interior zero byte, and appends the terminating zero. It returnsResult<CString, NulError>.CStris the borrowed form.CStr::from_ptrwraps a pointer you got from C, andto_str()checks that it is valid UTF-8.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
fn main() {
let c = CString::new("hello").expect("no interior NUL");
println!("{:?}", c.as_bytes_with_nul());
let bad = CString::new("he\0llo");
println!("interior NUL rejected: {}", bad.is_err());
let ptr: *const c_char = c.as_ptr();
let back: &CStr = unsafe { CStr::from_ptr(ptr) };
println!("{}", back.to_str().unwrap());
}The program prints [104, 101, 108, 108, 111, 0], then interior NUL rejected: true, then hello. The unsafe block is needed because from_ptr trusts that the pointer is valid and zero-terminated. Here that holds, because ptr comes from a live CString.
Since Rust 1.77 you can also write a C string literal such as c"hello". It has type &'static CStr, is checked at compile time, and needs no allocation.
Converting between the types
| From | To | How | Can fail? |
|---|---|---|---|
| `&str` | `&Path` | `Path::new(s)` | No |
| `&str` | `OsString` | `OsString::from(s)` | No |
| `&Path` | `Option<&str>` | `p.to_str()` | Yes, if not UTF-8 |
| `&Path` | `Cow<str>` | `p.to_string_lossy()` | No, but may change data |
| `OsString` | `String` | `into_string()` | Yes, returns the original on `Err` |
| `String` | `CString` | `CString::new(s)` | Yes, on interior NUL |
| `CString` | `String` | `into_string()` | Yes, if not UTF-8 |
The rule of thumb is that going toward String can fail, and going away from it usually cannot. The exception is CString, where the NUL rule makes the outward direction fallible too.
Decision criteria
- Use
Stringand&strfor text your program owns, such as messages, configuration values you parse, and identifiers. - Use
PathandPathBuffor anything that names a file or directory, even when you expect it to be UTF-8. - Use
OsStringfor environment variables, command-line arguments, and other values handed over by the OS, when you want to pass them through without loss. - Use
CStringonly at an FFI boundary, and create it as late as possible. - Convert to
Stringat the edge where you must display or process the text, and decide there how to handle failure: skip, report, or use the lossy form.
Exercise
A tool reads a file name from std::env::args_os() and prints it. Why is arg.into_string().unwrap() risky on Linux, and what could you use instead to print it without crashing?
Show answer
A Linux file name may contain bytes that are not valid UTF-8, so into_string() returns Err and unwrap() panics. Print arg.to_string_lossy() instead. It never fails and replaces invalid bytes with U+FFFD. If you must keep the exact name, keep it as an OsString and pass it directly to the file system functions.
Exercise
What does Path::new("/srv/app").join("/etc/passwd") return, and why does that matter when the second part comes from a user?
Show answer
It returns /etc/passwd. Joining an absolute path replaces the base instead of appending to it, so a user could point your program outside the intended directory. Reject absolute parts with is_absolute(), reject .. components, and canonicalize the result and compare it with the canonicalized base.
Exercise
CString::new("a\0b") returns Err. Why, and what type does the error have?
Show answer
A C string ends at the first zero byte, so a zero inside the data would make C code see only a. CString::new rejects it by returning Err(NulError).