How to initialize a global File structure? and other steps

⚓ Rust    📅 2025-09-01    👤 surdeus    👁️ 4      

surdeus

So I am new to rust.

I have a module that needs to have a persistent file open
and I need functions that can write to the file and eventually close the file.

Something I think would be very simple but I must be brain dead and dumb.

use std::fs::File;
use std::io::Write;

// Declare my file gobal.
// I understand a "FILE" is a struct but...
// There are only examples of using a File as a local variable not a global.
// and those examples do not initialize a File structure they use a let statement.
// with implied initialization instead of inline initialization.
static mut FH : File; // The compiler wants an initializer... what do I use?

// A function to open the file
pub fn open_the_file( filename : &str )
{
    // And this is wrong too
    // I understand File::Create() returns a Result<File,ERROR_MSG> enum.
    // I just want this to die/exit if an error occurs
    // I can't add .ok(), and I cannot add a ? to this. so how do I do that?
    FH = File::create(filename);
}

// a function to write data to the file
pub fn write_the_file( txt : &str )
{
    // All strings in rust are UTF8 sequences, aka: an u8 sequence
    // So how do I convert a &str into a &[u8] array?
    // I think it is exactly one of those right now
    FH.write( txt ); 
}

// and a function to close the file
pub fn close_the_file( )
{
        // The documentation says: "drop()" the handle
        // But the compiler says NO this is not allowed
         // so how do I close the file.
	drop( FH );
}

4 posts - 2 participants

Read full topic

🏷️ Rust_feed