godot::prelude

Struct GFile

pub struct GFile { /* private fields */ }
Expand description

Open a file for reading or writing.

This is a convenient wrapper around a FileAccess pointer with a unique reference, providing both safety and quality-of-life upgrades over the inner type:

  • Exposes reading and writing capabilities of FileAccess in a safe way, returning Result<T> instead of the T itself.
  • Makes the FileAccess handle exclusive to its instance, disallowing parallel reads and writes, which could introduce hard-to-track bugs due to unpredictable cursor movement. Exclusivity also ensures that when the GFile moves out of scope, the inner FileAccess does as well, automatically closing the file. Alternatively, you can drop() the GFile to close the file manually.
  • Implements useful Rust traits, namely: Read, BufRead, Write, Seek, allowing better file processing and integrating it with various tools in the Rust ecosystem (e.g. serialization).

Files by default are always opened with little-endian, as most files are saved as such. To switch to big-endian, use GFile::set_big_endian().

§ModeFlags

Every constructor opening the access to a file (open_* associated functions) accepts the flags parameter, opening the file for different types of operations. Regardless of the provided flags value, the cursor is always positioned at the beginning of the file upon opening. To adjust its position, use Seek-provided methods.

  • ModeFlags::READ opens the file for read operations.
  • ModeFlags::WRITE opens the file for write operations. If the file doesn’t exist at the provided path, it is created. If it exists, it is truncated after the file is closed.
  • ModeFlags::READ_WRITE opens the file for read and write operations. The file is not truncated after closing.
  • ModeFlags::WRITE_READ opens the file for read and write operations. If the file doesn’t exist at the provided path, it is created. If it exists, it is truncated.

§Examples

use godot::builtin::GString;
use godot::classes::file_access::ModeFlags;
use godot::tools::GFile;

fn save_game() -> Result<(), std::io::Error> {

    // Open file in write mode
    let mut my_file = GFile::open("user://save_game.sav", ModeFlags::WRITE)?;

    // Write some lines into it
    my_file.write_gstring_line("This is my saved game")?;
    my_file.write_gstring_line("I played for 5 minutes")?;

    Ok(())
    // When GFile gets out of scope, the file is closed.
}

fn load_game() -> Result<(), std::io::Error> {

    // Open file in read mode
    let mut my_file = GFile::open("user://save_game.sav", ModeFlags::READ)?;

    // Read lines
    let first_line = my_file.read_gstring_line()?;
    assert_eq!(first_line, GString::from("This is my saved game"));

    let second_line = my_file.read_gstring_line()?;
    assert_eq!(second_line, GString::from("I played for 5 minutes"));

    Ok(())
}

§See also

Implementations§

§

impl GFile

pub fn open(path: impl Into<GString>, flags: ModeFlags) -> Result<GFile, Error>

Open a file.

Opens a file located at path, creating new GFile object. For ModeFlags description check the GFile documentation.

pub fn open_compressed( path: impl Into<GString>, flags: ModeFlags, compression_mode: CompressionMode, ) -> Result<GFile, Error>

Open a compressed file.

Opens a compressed file located at path, creating new GFile object. Can read only files compressed by Godot compression formats. For ModeFlags description check the GFile documentation.

pub fn open_encrypted( path: impl Into<GString>, flags: ModeFlags, key: &PackedByteArray, ) -> Result<GFile, Error>

Open a file encrypted by byte key.

Opens a file encrypted by 32-byte long PackedByteArray located at path, creating new GFile object. For ModeFlags description check the GFile documentation.

pub fn open_encrypted_with_pass( path: impl Into<GString>, flags: ModeFlags, pass: GString, ) -> Result<GFile, Error>

Open a file encrypted by password.

Opens a file encrypted by a pass located at path, creating new GFile object. For ModeFlags description check the GFile documentation.

pub fn try_from_unique(file_access: Gd<FileAccess>) -> Result<GFile, IoError>

Creates new GFile from a FileAccess pointer with a reference count of 1.

For this method to work, the provided file_access must be unique – no other reference to it can exist. Its state is retained: both ModeFlags with which it was open and current internal cursor position.

See also into_inner for the opposite operation.

pub fn into_inner(self) -> Gd<FileAccess>

Retrieve inner pointer to the FileAccess.

This instance of GFile will be destroyed, but the file is kept open as long as there is at least one reference pointing to it. Its state is retained: both ModeFlags with which it was opened and current internal cursor position.

See also try_from_unique for the opposite operation.

pub fn modified_time(path: impl Into<GString>) -> Result<u64, Error>

Get last modified time as a Unix timestamp.

pub fn md5(path: impl Into<GString>) -> Result<GString, Error>

Calculates the MD5 checksum of the file at the given path.

pub fn sha256(path: impl Into<GString>) -> Result<GString, Error>

Calculates the SHA-256 checksum of the file at the given path.

pub fn read_u8(&mut self) -> Result<u8, Error>

Reads the next byte from the file as u8.

Underlying Godot method: FileAccess::get_8.

pub fn read_u16(&mut self) -> Result<u16, Error>

Reads the next 2 bytes from the file as u16.

Underlying Godot method: FileAccess::get_16.

pub fn read_u32(&mut self) -> Result<u32, Error>

Reads the next 4 bytes from the file as u32.

Underlying Godot method: FileAccess::get_32.

pub fn read_u64(&mut self) -> Result<u64, Error>

Reads the next 8 bytes from the file as u64.

Underlying Godot method: FileAccess::get_64.

pub fn read_pascal_string(&mut self) -> Result<GString, Error>

Reads a Pascal string (length-prefixed) from the current position.

A Pascal string is useful for writing and retrieving variable-length string data from binary files. It is saved with a length prefix (as opposed to C strings, which end with a null terminator). Text is interpreted as UTF-8 encoded.

See also:

pub fn read_gstring_line(&mut self) -> Result<GString, Error>

Reads the next line of the file as GString.

To retrieve the file as String instead, use the Read trait method read_to_string().

Underlying Godot method: FileAccess::get_line.

pub fn read_as_gstring_entire( &mut self, skip_cr: bool, ) -> Result<GString, Error>

Reads the whole file as UTF-8 GString.

If skip_cr is set to true, carriage return ('\r') will be ignored, and only line feed ('\n') indicates a new line.

To retrieve the file as String instead, use the Read trait method read_to_string().

Underlying Godot method: FileAccess::get_as_text.

pub fn read_csv_line( &mut self, delim: impl Into<GString>, ) -> Result<PackedStringArray, Error>

Reads the next line of the file in delimiter-separated file.

For reading traditional CSV format, provide comma (',') as delim.

Underlying Godot method: FileAccess::get_csv_line.

pub fn read_f32(&mut self) -> Result<f32, Error>

Reads the next 4 bytes from file as f32.

Underlying Godot method: FileAccess::get_float.

pub fn read_f64(&mut self) -> Result<f64, Error>

Reads the next 8 bytes from file as f64.

Underlying Godot method: FileAccess::get_double.

pub fn read_real(&mut self) -> Result<f32, Error>

Reads the next 4 or 8 bytes from file as real, depending on configuration.

See real type for more information.

Underlying Godot method: FileAccess::get_float or FileAccess::get_double (note that FileAccess::get_real does not return an actual real).

Warning: Since this involves a configuration-dependent type, you may not be able to read the value back if Godot uses different precision setting (single or double) than the one used to write the value.

pub fn read_variant(&mut self, allow_objects: bool) -> Result<Variant, Error>

Reads the next Variant value from file.

If allow_objects is set to true, objects will be decoded.

Warning: Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources, to avoid potential security threats such as remote code execution.

Underlying Godot method: FileAccess::get_var.

pub fn write_u8(&mut self, value: u8) -> Result<(), Error>

Writes u8 as the next byte in the file.

Underlying Godot method: FileAccess::store_8.

pub fn write_u16(&mut self, value: u16) -> Result<(), Error>

Writes u16 as the next 2 bytes in the file.

Underlying Godot method: FileAccess::store_16.

pub fn write_u32(&mut self, value: u32) -> Result<(), Error>

Writes u32 as the next 4 bytes in the file.

Underlying Godot method: FileAccess::store_32.

pub fn write_u64(&mut self, value: u64) -> Result<(), Error>

Writes u64 as the next 8 bytes in the file.

Underlying Godot method: FileAccess::store_64.

pub fn write_f32(&mut self, value: f32) -> Result<(), Error>

Writes f32 as the 32 bits in the file.

Underlying Godot method: FileAccess::store_float.

pub fn write_f64(&mut self, value: f64) -> Result<(), Error>

Writes f64 as the 64 bits in the file.

Underlying Godot method: FileAccess::store_double.

pub fn write_real(&mut self, value: f32) -> Result<(), Error>

Writes a real (f32 or f64) as the next 4 or 8 bytes in the file, depending on configuration.

See real type for more information.

Underlying Godot method: FileAccess::store_float or FileAccess::store_double (note that FileAccess::store_real does not accept an actual real).

Warning: Since this involves a configuration-dependent type, you may not be able to read the value back if Godot uses different precision setting (single or double) than the one used to write the value.

pub fn write_gstring(&mut self, value: impl Into<GString>) -> Result<(), Error>

Writes string to the file.

This function is meant to be used in text files. To store a string in a binary file, use store_pascal_string()

Underlying Godot method: FileAccess::store_string.

pub fn write_pascal_string( &mut self, value: impl Into<GString>, ) -> Result<(), Error>

Writes string to the file as Pascal String.

This function is meant to be used in binary files. To store a string in a text file, use store_string()

Pascal String is useful for writing and retrieving verying-length string data from binary files. It is saved with length-prefix, instead of null terminator as in C strings.

See also:

pub fn write_gstring_line( &mut self, value: impl Into<GString>, ) -> Result<(), Error>

Write string to the file as a line.

Underlying Godot method: FileAccess::store_line.

pub fn write_csv_line( &mut self, values: &PackedStringArray, delim: impl Into<GString>, ) -> Result<(), Error>

Write PackedStringArray to the file as delimited line.

For writing traditional CSV format, provide comma (',') as delim.

Underlying Godot method: FileAccess::store_csv_line.

pub fn write_variant( &mut self, value: Variant, full_objects: bool, ) -> Result<(), Error>

Write Variant to the file.

If full_objects is set to true, encoding objects is allowed (and can potentially include GDScript code). Not all properties of the Variant are included. Only properties that are exported (have #[export] derive attribute) will be serialized.

Underlying Godot method: FileAccess::store_var.

pub fn set_big_endian(&mut self, value: bool)

Set true to use big-endian, false to use little-endian.

Endianness can be set mid-file, not only at the start position. It makes it possible to write different sections of binary file with different endianness, though it is not recommended - can lead to confusion and mistakes during consequent read operations.

pub fn is_big_endian(&self) -> bool

Check endianness of current file access.

pub fn path(&self) -> GString

Get path of the opened file.

pub fn path_absolute(&self) -> GString

Get absolute path of the opened file.

pub fn position(&self) -> u64

Returns the current cursor position.

pub fn length(&self) -> u64

Get file length in bytes.

pub fn eof_reached(&self) -> bool

Checks if the file cursor has read past the end of the file.

Trait Implementations§

§

impl BufRead for GFile

§

fn fill_buf(&mut self) -> Result<&[u8], Error>

Returns the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more
§

fn consume(&mut self, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to read. Read more
source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if the underlying Read has any data left to be read. Read more
1.0.0 · source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
1.83.0 · source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
1.0.0 · source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
§

impl Read for GFile

§

fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
1.36.0 · source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
§

impl Seek for GFile

§

fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>

Seek to an offset, in bytes, in a stream. Read more
1.55.0 · source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.51.0 · source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.80.0 · source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
§

impl Write for GFile

§

fn write(&mut self, buf: &[u8]) -> Result<usize, Error>

Writes a buffer into this writer, returning how many bytes were written. Read more
§

fn flush(&mut self) -> Result<(), Error>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl Freeze for GFile

§

impl RefUnwindSafe for GFile

§

impl !Send for GFile

§

impl !Sync for GFile

§

impl Unpin for GFile

§

impl UnwindSafe for GFile

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.