coding-horror/basic-computer-games · error

Invalid file path!

Error message

Invalid file path!

What it means

This panic is triggered by `.expect("Invalid file path!")` on `File::create(path)` in Splat's `Stats::new()` (line 43), where `path` is the hardcoded string `"src/stats.txt"`. `File::create` returns `Err` for many reasons beyond an invalid path — missing parent directory, insufficient permissions, read-only filesystem, or disk full. The message implies the path string is wrong, which is only one possible cause.

Source

Thrown at 81_Splat/rust/src/stats.rs:43

                let stats: Vec<&str> = stats.trim().split(",").collect();

                for s in stats {
                    if s.is_empty() {
                        continue;
                    }

                    let s = s.parse::<f32>().expect("Corrupt stats file!");
                    altitudes.push(s);
                }

                return Some(Stats { altitudes });
            } else {
                println!("PREVIOUS GAME DATA NOT FOUND!");

                if !utility::prompt_bool("WOULD YOU LIKE TO CREATE ONE?", false) {
                    return None;
                } else {
                    let mut file = File::create(path).expect("Invalid file path!");
                    file.write_all("".as_bytes())
                        .expect("Could not create file!");

                    return Some(Stats {
                        altitudes: Vec::new(),
                    });
                }
            }
        }

        println!("\nRESULTS OF THIS SESSION WILL NOT BE SAVED.");
        None
    }

    pub fn add_altitude(&mut self, a: f32) {
        let all_jumps = self.altitudes.len() + 1;
        let mut placement = all_jumps;

View on GitHub (pinned to 5301155192)

Solutions

  1. Use an absolute path or a platform-appropriate config/data directory (e.g., `dirs::data_dir()`) instead of the hardcoded relative `src/stats.txt`.
  2. Create the parent directory with `std::fs::create_dir_all` before `File::create`.
  3. Replace `.expect` with proper error handling that reports the actual `io::Error` to the user.
  4. Run the binary from the project root or provide a `--data-dir` CLI flag.

Example fix

// before
let path = "src/stats.txt";
let mut file = File::create(path).expect("Invalid file path!");

// after
let path = "src/stats.txt";
if let Some(parent) = std::path::Path::new(path).parent() {
    let _ = std::fs::create_dir_all(parent);
}
let mut file = match File::create(path) {
    Ok(f) => f,
    Err(e) => { eprintln!("Cannot create stats file: {}", e); return None; }
};
Defensive patterns

Strategy: validation

Validate before calling

// Validate the path and parent directory before File::create
use std::path::Path;
let path = Path::new("src/stats.txt");
if let Some(parent) = path.parent() {
    std::fs::create_dir_all(parent).ok();
}
assert!(path.parent().map(|p| p.exists()).unwrap_or(true),
    "Parent directory does not exist");

Type guard

fn can_create_file(path: &str) -> bool {
    let p = std::path::Path::new(path);
    p.parent().map(|dir| dir.exists() || std::fs::create_dir_all(dir).is_ok())
        .unwrap_or(true)
}

Try / catch

let mut file = match File::create(path) {
    Ok(f) => f,
    Err(e) => {
        eprintln!("Cannot create stats file '{}': {}", path, e);
        return None;
    }
};

Prevention

When it happens

Trigger: The `src/` directory does not exist in the current working directory (e.g., the binary is run from a different working directory than the project root). The user lacks write permissions. The filesystem is read-only. The path exists as a directory rather than a file.

Common situations: Running the compiled binary from `target/release/` or any directory other than the project root — the relative path `src/stats.txt` resolves to a non-existent `src/` parent. Deploying the binary without the `src/` directory. Running on a read-only filesystem (container, Live CD). Permission denied in shared hosting.

Related errors


AI-assisted analysis of coding-horror/basic-computer-games@5301155192 (2026-08-13). Data as JSON: /api/errors/6cbde88420410e7c. Report an issue: GitHub.