OpenTTD Source: src/fileio.cpp File Reference

OpenTTD Source 1.11.0-RC1

Data Structures | Macros | Typedefs | Functions | Variables
fileio.cpp File Reference
`#include "stdafx.h"`
`#include "fileio_func.h"`
`#include "debug.h"`
`#include "fios.h"`
`#include "string_func.h"`
`#include "tar_type.h"`
`#include <unistd.h>`
`#include <pwd.h>`
`#include <sys/stat.h>`
`#include <array>`
`#include <sstream>`
`#include "safeguards.h"`

Go to the source code of this file.

## Data Structures
struct | Fio
| Structure for keeping several open files with just one data buffer. More...

## Macros
#define | FIO_BUFFER_SIZE 512
| Size of the Fio data buffer.

## Typedefs
typedef std::map< std::string, std::string > | TarLinkList

## Functions
size_t | FioGetPos ()
| Get position in the current file. More...
const char * | FioGetFilename (uint8 slot)
| Get the filename associated with a slot. More...
void | FioSeekTo (size_t pos, int mode)
| Seek in the current file. More...
void | FioSeekToFile (uint8 slot, size_t pos)
| Switch to a different file and seek to a position. More...
byte | FioReadByte ()
| Read a byte from the file. More...
void | FioSkipBytes (int n)
| Skip n bytes ahead in the file. More...
uint16 | FioReadWord ()
| Read a word (16 bits) from the file (in low endian format). More...
uint32 | FioReadDword ()
| Read a double word (32 bits) from the file (in low endian format). More...
void | FioReadBlock (void *ptr, size_t size)
| Read a block. More...
static void | FioCloseFile (int slot)
| Close the file at the given slot number. More...
void | FioCloseAll ()
| Close all slotted open files.
void | FioOpenFile (int slot, const std::string &filename, Subdirectory subdir)
| Open a slotted file. More...
bool | IsValidSearchPath (Searchpath sp)
| Checks whether the given search path is a valid search path. More...
bool | FioCheckFileExists (const std::string &filename, Subdirectory subdir)
| Check whether the given file exists. More...
bool | FileExists (const std::string &filename)
| Test whether the given filename exists. More...
void | FioFCloseFile (FILE *f)
| Close a file in a safe way.
std::string | FioFindFullPath (Subdirectory subdir, const char *filename)
| Find a path to the filename in one of the search directories. More...
std::string | FioGetDirectory (Searchpath sp, Subdirectory subdir)
std::string | FioFindDirectory (Subdirectory subdir)
static FILE * | FioFOpenFileSp (const std::string &filename, const char *mode, Searchpath sp, Subdirectory subdir, size_t *filesize)
FILE * | FioFOpenFileTar (const TarFileListEntry &entry, size_t *filesize)
| Opens a file from inside a tar archive. More...
FILE * | FioFOpenFile (const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
| Opens a OpenTTD file somewhere in a personal or global directory. More...
void | FioCreateDirectory (const std::string &name)
| Create a directory with the given name If the parent directory does not exist, it will try to create that as well. More...
void | AppendPathSeparator (std::string &buf)
| Appends, if necessary, the path separator character to the end of the string. More...
static void | TarAddLink (const std::string &srcParam, const std::string &destParam, Subdirectory subdir)
static void | SimplifyFileName (char *name)
| Simplify filenames from tars. More...
bool | ExtractTar (const std::string &tar_filename, Subdirectory subdir)
| Extract the tar with the given filename in the directory where the tar resides. More...
static bool | ChangeWorkingDirectoryToExecutable (const char *exe)
| Changes the working directory to the path of the give executable. More...
bool | DoScanWorkingDirectory ()
| Whether we should scan the working directory. More...
static std::string | GetHomeDir ()
| Gets the home directory of the user. More...
void | DetermineBasePaths (const char *exe)
| Determine the base (personal dir and game data dir) paths. More...
void | DeterminePaths (const char *exe)
| Acquire the base paths (personal dir and game data dir), fill all other paths (save dir, autosave dir etc) and make the save and scenario directories. More...
void | SanitizeFilename (char *filename)
| Sanitizes a filename, i.e. More...
std::unique_ptr< char > | ReadFileToMem (const std::string &filename, size_t &lenp, size_t maxsize)
| Load a file into memory. More...
static bool | MatchesExtension (const char *extension, const char *filename)
| Helper to see whether a given filename matches the extension. More...
static uint | ScanPath (FileScanner *fs, const char *extension, const char *path, size_t basepath_length, bool recursive)
| Scan a single directory (and recursively its children) and add any graphics sets that are found. More...
static uint | ScanTar (FileScanner *fs, const char *extension, TarFileList::iterator tar)
| Scan the given tar and add graphics sets when it finds one. More...

## Variables
static Fio | _fio
| Fio instance.
static bool | _do_scan_working_directory = true
| Whether the working directory should be scanned.
std::string | _config_file
| Configuration file of OpenTTD.
std::string | _highscore_file
| The file to store the highscore data in.
static const char *const | _subdirs []
std::array< std::string, NUM_SEARCHPATHS > | _searchpaths
| The search paths OpenTTD could search through. More...
std::array< TarList, NUM_SUBDIRS > | _tar_list
TarFileList | _tar_filelist [NUM_SUBDIRS]
static TarLinkList | _tar_linklist [NUM_SUBDIRS]
| List of directory links.
std::string | _personal_dir
| custom directory for personal settings, saves, newgrf, etc.

## Detailed Description

Standard In/Out file operations

Definition in file fileio.cpp.

## Function Documentation

## ◆ AppendPathSeparator()

void AppendPathSeparator | ( | std::string & | buf | ) |

Appends, if necessary, the path separator character to the end of the string.

It does not add the path separator to zero-sized strings.

Parameters

  buf | string to append the separator to

Returns
  true iff the operation succeeded

Definition at line 520 of file fileio.cpp.

Referenced by FileScanner::Scan().

## ◆ ChangeWorkingDirectoryToExecutable()

static bool ChangeWorkingDirectoryToExecutable | ( | const char * | exe | ) |
| static

Changes the working directory to the path of the give executable.

For OSX application bundles '.app' is the required extension of the bundle, so when we crop the path to there, when can remove the name of the bundle in the same way we remove the name from the executable name.

Parameters

  exe | the path to the executable

Definition at line 924 of file fileio.cpp.

## ◆ DetermineBasePaths()

void DetermineBasePaths | ( | const char * | exe | ) |

Determine the base (personal dir and game data dir) paths.

Parameters

  exe | the path to the executable

Definition at line 1000 of file fileio.cpp.

References GetHomeDir().

Referenced by DeterminePaths().

## ◆ DeterminePaths()

void DeterminePaths | ( | const char * | exe | ) |

Acquire the base paths (personal dir and game data dir), fill all other paths (save dir, autosave dir etc) and make the save and scenario directories.

Parameters

  exe | the path from the current path to the executable

Definition at line 1127 of file fileio.cpp.

References DetermineBasePaths(), and GetHomeDir().

## ◆ DoScanWorkingDirectory()

bool DoScanWorkingDirectory | ( |  | ) |

Whether we should scan the working directory.

It should not be scanned if it's the root or the home directory as in both cases a big data directory can cause huge amounts of unrelated files scanned. Furthermore there are nearly no use cases for the home/root directory to have OpenTTD directories.

Returns
  true if it should be scanned.

Definition at line 958 of file fileio.cpp.

References _searchpaths, and SP_WORKING_DIR.

## ◆ ExtractTar()

bool ExtractTar | ( | const std::string & | tar_filename,
|  | Subdirectory | subdir
| ) |  |

Extract the tar with the given filename in the directory where the tar resides.

Parameters

  tar_filename | the name of the tar to extract.
  subdir | The sub directory the tar is in.

Returns
  false on failure.

Definition at line 845 of file fileio.cpp.

## ◆ FileExists()

bool FileExists | ( | const std::string & | filename | ) |

Test whether the given filename exists.

Parameters

  filename | the file to test.

Returns
  true if and only if the file exists.

Definition at line 280 of file fileio.cpp.

References OTTD2FS().

## ◆ FioCheckFileExists()

bool FioCheckFileExists | ( | const std::string & | filename,
|  | Subdirectory | subdir
| ) |  |

Check whether the given file exists.

Parameters

  filename | the file to try for existence.
  subdir | the subdirectory to look in

Returns
  true if and only if the file can be opened

Definition at line 266 of file fileio.cpp.

References FioFCloseFile(), and FioFOpenFile().

Referenced by FillGRFDetails(), GetMusicCatEntryData(), GetMusicCatEntryName(), GRFLoadConfig(), and SaveLoadWindow::OnTimeout().

## ◆ FioCloseFile()

static void FioCloseFile | ( | int | slot | ) |
| inlinestatic

Close the file at the given slot number.

Parameters

  slot | File index to close.

Definition at line 171 of file fileio.cpp.

References _fio, Fio::handles, and Fio::shortnames.

Referenced by FioCloseAll(), and FioOpenFile().

## ◆ FioCreateDirectory()

void FioCreateDirectory | ( | const std::string & | name | ) |

Create a directory with the given name If the parent directory does not exist, it will try to create that as well.

Parameters

  name | the new name of the directory

Definition at line 490 of file fileio.cpp.

## ◆ FioFindFullPath()

std::string FioFindFullPath | ( | Subdirectory | subdir,
|  | const char * | filename
| ) |  |

Find a path to the filename in one of the search directories.

Parameters

  subdir | Subdirectory to try.
  filename | Filename to look for.

Returns
  String containing the path if the path was found, else an empty string.

Definition at line 299 of file fileio.cpp.

References FOR_ALL_SEARCHPATHS, and NUM_SUBDIRS.

Referenced by MidiFile::GetSMFFile().

## ◆ FioFOpenFile()

FILE* FioFOpenFile | ( | const std::string & | filename,
|  | const char * | mode,
|  | Subdirectory | subdir,
|  | size_t * | filesize
| ) |  |

Opens a OpenTTD file somewhere in a personal or global directory.

Parameters

  filename | Name of the file to open.
  subdir | Subdirectory to open.

Returns
  File handle of the opened file, or `nullptr` if the file is not available.

Definition at line 406 of file fileio.cpp.

References FOR_ALL_SEARCHPATHS, NO_DIRECTORY, and NUM_SUBDIRS.

Referenced by ScriptFileChecksumCreator::AddFile(), ScenarioScanner::AddFile(), CalcGRFMD5Sum(), MD5File::CheckMD5(), GraphicsSet::CheckMD5(), FioCheckFileExists(), FioOpenFile(), GetFileTitle(), MidiFile::LoadFile(), Squirrel::LoadFile(), TextfileWindow::LoadTextfile(), IniFile::OpenFile(), ReadRawLanguageStrings(), MidiFile::ReadSMFHeader(), CrashLog::WriteCrashLog(), and MidiFile::WriteSMF().

## ◆ FioFOpenFileTar()

FILE* FioFOpenFileTar | ( | const TarFileListEntry & | entry,
|  | size_t * | filesize
| ) |  |

Opens a file from inside a tar archive.

Parameters

  | entry | The entry to open.
  [out] | filesize | If not `nullptr`, size of the opened file.

Returns
  File handle of the opened file, or `nullptr` if the file is not available.

Note
  The file is read from within the tar file, and may not return `EOF` after reading the whole file.

Definition at line 386 of file fileio.cpp.

## ◆ FioGetFilename()

const char* FioGetFilename | ( | uint8 | slot | ) |

Get the filename associated with a slot.

Parameters

  slot | Index of queried file.

Returns
  Name of the file.

Definition at line 69 of file fileio.cpp.

References _fio, and Fio::shortnames.

Referenced by WarnCorruptSprite().

## ◆ FioGetPos()

size_t FioGetPos | ( |  | ) |

Get position in the current file.

Returns
  Position in the file.

Definition at line 59 of file fileio.cpp.

References _fio, Fio::buffer_end, and Fio::pos.

Referenced by FioReadBlock(), FioSeekTo(), GetGRFContainerVersion(), LoadNextSprite(), and ReadGRFSpriteOffsets().

## ◆ FioOpenFile()

void FioOpenFile | ( | int | slot,
|  | const std::string & | filename,
|  | Subdirectory | subdir
| ) |  |

Open a slotted file.

Parameters

  slot | Index to assign.
  filename | Name of the file at the disk.
  subdir | The sub directory to search this file in.

Definition at line 196 of file fileio.cpp.

References _fio, Fio::filenames, FioCloseFile(), FioFOpenFile(), Fio::handles, and usererror().

Referenced by GetMusicCatEntryData(), GetMusicCatEntryName(), LoadGrfFile(), and LoadGrfFileIndexed().

## ◆ FioReadBlock()

void FioReadBlock | ( | void * | ptr,
|  | size_t | size
| ) |  |

Read a block.

Parameters

  ptr | Destination buffer.
  size | Number of bytes to read.

Definition at line 161 of file fileio.cpp.

References _fio, Fio::cur_fh, FioGetPos(), FioSeekTo(), and Fio::pos.

Referenced by GetMusicCatEntryData(), and GetMusicCatEntryName().

## ◆ FioReadByte()

byte FioReadByte | ( |  | ) |

Read a byte from the file.

Returns
  Read byte.

Definition at line 107 of file fileio.cpp.

References _fio, Fio::buffer_end, Fio::buffer_start, Fio::cur_fh, FIO_BUFFER_SIZE, and Fio::pos.

Referenced by DecodeSingleSprite(), FioReadWord(), FioSkipBytes(), GetGRFContainerVersion(), GetMusicCatEntryData(), GetMusicCatEntryName(), LoadGrfFile(), LoadGrfFileIndexed(), LoadNextSprite(), and SkipSpriteData().

## ◆ FioReadDword()

uint32 FioReadDword | ( |  | ) |

Read a double word (32 bits) from the file (in low endian format).

Returns
  Read word.

Definition at line 150 of file fileio.cpp.

References FioReadWord().

Referenced by GetMusicCatEntryData(), GetMusicCatEntryName(), ImportGRFSound(), LoadNextSprite(), and ReadGRFSpriteOffsets().

## ◆ FioReadWord()

uint16 FioReadWord | ( |  | ) |

Read a word (16 bits) from the file (in low endian format).

Returns
  Read word.

Definition at line 140 of file fileio.cpp.

References FioReadByte().

Referenced by FioReadDword(), GetGRFContainerVersion(), ImportGRFSound(), and LoadNextSprite().

## ◆ FioSeekTo()

void FioSeekTo | ( | size_t | pos,
|  | int | mode
| ) |  |

Seek in the current file.

Parameters

  pos | New position.
  mode | Type of seek (`SEEK_CUR` means pos is relative to current position, `SEEK_SET` means pos is absolute).

Definition at line 79 of file fileio.cpp.

References _fio, Fio::buffer_end, Fio::buffer_start, Fio::cur_fh, DEBUG, Fio::filename, FIO_BUFFER_SIZE, FioGetPos(), and Fio::pos.

Referenced by FioReadBlock(), FioSeekToFile(), GetGRFContainerVersion(), GetMusicCatEntryData(), GetMusicCatEntryName(), and ReadGRFSpriteOffsets().

## ◆ FioSeekToFile()

void FioSeekToFile | ( | uint8 | slot,
|  | size_t | pos
| ) |  |

Switch to a different file and seek to a position.

Parameters

  slot | Slot number of the new file.
  pos | New absolute position in the new file.

Definition at line 94 of file fileio.cpp.

References _fio, Fio::cur_fh, Fio::filename, Fio::filenames, FioSeekTo(), and Fio::handles.

## ◆ FioSkipBytes()

void FioSkipBytes | ( | int | n | ) |

Skip n bytes ahead in the file.

Parameters

  n | Number of bytes to skip reading.

Definition at line 124 of file fileio.cpp.

References _fio, Fio::buffer_end, and FioReadByte().

Referenced by GetMusicCatEntryData(), LoadNextSprite(), ReadGRFSpriteOffsets(), and SkipSpriteData().

## ◆ GetHomeDir()

static std::string GetHomeDir | ( |  | ) |
| static

Gets the home directory of the user.

May return an empty string in the unlikely scenario that the home directory cannot be found.

Returns
  User's home directory

Definition at line 980 of file fileio.cpp.

Referenced by DetermineBasePaths(), and DeterminePaths().

## ◆ IsValidSearchPath()

bool IsValidSearchPath | ( | Searchpath | sp | ) |

Checks whether the given search path is a valid search path.

Parameters

  sp | the search path to check

Returns
  true if the search path is valid

Definition at line 255 of file fileio.cpp.

References _searchpaths.

## ◆ MatchesExtension()

static bool MatchesExtension | ( | const char * | extension,
|  | const char * | filename
| ) |  |
| static

Helper to see whether a given filename matches the extension.

Parameters

  extension | The extension to look for.
  filename | The filename to look in for the extension.

Returns
  True iff the extension is nullptr, or the filename ends with it.

Definition at line 1289 of file fileio.cpp.

Referenced by ScanTar().

## ◆ ReadFileToMem()

std::unique_ptr<char> ReadFileToMem | ( | const std::string & | filename,
|  | size_t & | lenp,
|  | size_t | maxsize
| ) |  |

Load a file into memory.

Parameters

  | filename | Name of the file to load.
  [out] | lenp | Length of loaded data.
  | maxsize | Maximum size to load.

Returns
  Pointer to new memory containing the loaded data, or `nullptr` if loading failed.

Note
  If maxsize less than the length of the file, loading fails.

Definition at line 1259 of file fileio.cpp.

Referenced by ReadLanguagePack().

## ◆ SanitizeFilename()

void SanitizeFilename | ( | char * | filename | ) |

Sanitizes a filename, i.e.

removes all illegal characters from it.

Parameters

  filename | the "\0" terminated filename

Definition at line 1237 of file fileio.cpp.

## ◆ ScanPath()

static uint ScanPath | ( | FileScanner * | fs,
|  | const char * | extension,
|  | const char * | path,
|  | size_t | basepath_length,
|  | bool | recursive
| ) |  |
| static

Scan a single directory (and recursively its children) and add any graphics sets that are found.

Parameters

  fs | the file scanner to add the files to
  extension | the extension of files to search for.
  path | full path we're currently at
  basepath_length | from where in the path are we 'based' on the search path
  recursive | whether to recursively search the sub directories

Definition at line 1306 of file fileio.cpp.

Referenced by FileScanner::Scan().

## ◆ ScanTar()

static uint ScanTar | ( | FileScanner * | fs,
|  | const char * | extension,
|  | TarFileList::iterator | tar
| ) |  |
| static

Scan the given tar and add graphics sets when it finds one.

Parameters

  fs | the file scanner to scan for
  extension | the extension of files to search for.
  tar | the tar to search in.

Definition at line 1348 of file fileio.cpp.

References FileScanner::AddFile(), and MatchesExtension().

## ◆ SimplifyFileName()

static void SimplifyFileName | ( | char * | name | ) |
| static

Simplify filenames from tars.

Replace '/' by #PATHSEPCHAR, and force 'name' to lowercase.

Parameters

  name | Filename to process.

Definition at line 553 of file fileio.cpp.

References strtolower().

## Variable Documentation

## ◆ _searchpaths

std::array<std::string, NUM_SEARCHPATHS> _searchpaths

The search paths OpenTTD could search through.

At least one of the slots has to be filled with a path. An empty string tells that there is no such path for the current operating system.

Definition at line 235 of file fileio.cpp.

Referenced by DoScanWorkingDirectory(), and IsValidSearchPath().

## ◆ _subdirs

const char* const _subdirs[]
| static

Initial value:
= {
"",
"save" PATHSEP,
"save" PATHSEP "autosave" PATHSEP,
"scenario" PATHSEP,
"scenario" PATHSEP "heightmap" PATHSEP,
"gm" PATHSEP,
"data" PATHSEP,
"baseset" PATHSEP,
"newgrf" PATHSEP,
"lang" PATHSEP,
"ai" PATHSEP,
"ai" PATHSEP "library" PATHSEP,
"game" PATHSEP,
"game" PATHSEP "library" PATHSEP,
"screenshot" PATHSEP,
}

Definition at line 218 of file fileio.cpp.