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, returningResult<T>
instead of theT
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 theGFile
moves out of scope, the innerFileAccess
does as well, automatically closing the file. Alternatively, you candrop()
theGFile
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 providedpath
, 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 providedpath
, 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
FileAccess
class in Rust.- Godot documentation for
FileAccess
.
Implementations§
§impl GFile
impl GFile
pub fn open_compressed(
path: impl Into<GString>,
flags: ModeFlags,
compression_mode: CompressionMode,
) -> Result<GFile, Error>
pub fn open_compressed( path: impl Into<GString>, flags: ModeFlags, compression_mode: CompressionMode, ) -> Result<GFile, Error>
pub fn open_encrypted(
path: impl Into<GString>,
flags: ModeFlags,
key: &PackedByteArray,
) -> Result<GFile, Error>
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>
pub fn open_encrypted_with_pass( path: impl Into<GString>, flags: ModeFlags, pass: GString, ) -> Result<GFile, Error>
pub fn try_from_unique(file_access: Gd<FileAccess>) -> Result<GFile, IoError>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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
).
pub fn read_variant(&mut self, allow_objects: bool) -> Result<Variant, Error>
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.
Underlying Godot method:
FileAccess::get_var
.
pub fn write_u8(&mut self, value: u8) -> Result<(), Error>
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>
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>
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>
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>
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>
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>
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
).
pub fn write_gstring(&mut self, value: impl Into<GString>) -> Result<(), Error>
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>
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>
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>
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>
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)
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
pub fn is_big_endian(&self) -> bool
Check endianness of current file access.
pub fn path_absolute(&self) -> GString
pub fn path_absolute(&self) -> GString
Get absolute path of the opened file.
pub fn eof_reached(&self) -> bool
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
impl BufRead for GFile
§fn fill_buf(&mut self) -> Result<&[u8], Error>
fn fill_buf(&mut self) -> Result<&[u8], Error>
§fn consume(&mut self, amt: usize)
fn consume(&mut self, amt: usize)
amt
bytes have been consumed from the buffer,
so they should no longer be returned in calls to read
. Read moresource§fn has_data_left(&mut self) -> Result<bool, Error>
fn has_data_left(&mut self) -> Result<bool, Error>
buf_read_has_data_left
)Read
has any data left to be read. Read more1.83.0 · source§fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
byte
or EOF is reached. Read more1.0.0 · source§fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
0xA
byte) is reached, and append
them to the provided String
buffer. Read more§impl Read for GFile
impl Read for GFile
§fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
1.36.0 · source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read
, except that it reads into a slice of buffers. Read moresource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf
. Read more1.0.0 · source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf
. Read more1.6.0 · source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf
. Read moresource§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)cursor
. Read more1.0.0 · source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read more§impl Seek for GFile
impl Seek for GFile
§fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>
fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>
1.55.0 · source§fn rewind(&mut self) -> Result<(), Error>
fn rewind(&mut self) -> Result<(), Error>
source§fn stream_len(&mut self) -> Result<u64, Error>
fn stream_len(&mut self) -> Result<u64, Error>
seek_stream_len
)§impl Write for GFile
impl Write for GFile
§fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
§fn flush(&mut self) -> Result<(), Error>
fn flush(&mut self) -> Result<(), Error>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)