Changeset - r17895:0fe3145edf8a
[Not reviewed]
master
0 1 0
alberth - 13 years ago 2011-08-01 19:36:11
alberth@openttd.org
(svn r22709) -Doc: Doxyment fileio.cpp.
1 file changed with 76 insertions and 12 deletions:
0 comments (0 inline, 0 general)
src/fileio.cpp
Show inline comments
 
@@ -21,28 +21,24 @@
 
#elif defined(__HAIKU__)
 
#include <Path.h>
 
#include <storage/FindDirectory.h>
 
#else
 
#if defined(OPENBSD) || defined(DOS)
 
#include <unistd.h>
 
#endif
 
#include <pwd.h>
 
#endif
 
#include <sys/stat.h>
 
#include <algorithm>
 

	
 
/*************************************************/
 
/* FILE IO ROUTINES ******************************/
 
/*************************************************/
 

	
 
/** Size of the #Fio data buffer. */
 
#define FIO_BUFFER_SIZE 512
 

	
 
/** Structure for keeping several open files with just one data buffer. */
 
struct Fio {
 
	byte *buffer, *buffer_end;             ///< position pointer in local buffer and last valid byte of buffer
 
	size_t pos;                            ///< current (system) position in file
 
	FILE *cur_fh;                          ///< current file handle
 
	const char *filename;                  ///< current filename
 
	FILE *handles[MAX_FILE_SLOTS];         ///< array of file handles we can have open
 
	byte buffer_start[FIO_BUFFER_SIZE];    ///< local buffer when read from file
 
	const char *filenames[MAX_FILE_SLOTS]; ///< array of filenames we (should) have open
 
@@ -52,133 +48,171 @@ struct Fio {
 
	uint usage_count[MAX_FILE_SLOTS];      ///< count how many times this file has been opened
 
#endif /* LIMITED_FDS */
 
};
 

	
 
static Fio _fio; ///< #Fio instance.
 

	
 
/** Whether the working directory should be scanned. */
 
static bool _do_scan_working_directory = true;
 

	
 
extern char *_config_file;
 
extern char *_highscore_file;
 

	
 
/** Get current position in file. */
 
/**
 
 * Get position in the current file.
 
 * @return Position in the file.
 
 */
 
size_t FioGetPos()
 
{
 
	return _fio.pos + (_fio.buffer - _fio.buffer_end);
 
}
 

	
 
/**
 
 * Get the filename associated with a slot.
 
 * @param slot Index of queried file.
 
 * @return Name of the file.
 
 */
 
const char *FioGetFilename(uint8 slot)
 
{
 
	return _fio.shortnames[slot];
 
}
 

	
 
/**
 
 * Seek in the current file.
 
 * @param pos New position.
 
 * @param mode Type of seek (\c SEEK_CUR means \a pos is relative to current position, \c SEEK_SET means \a pos is absolute).
 
 */
 
void FioSeekTo(size_t pos, int mode)
 
{
 
	if (mode == SEEK_CUR) pos += FioGetPos();
 
	_fio.buffer = _fio.buffer_end = _fio.buffer_start + FIO_BUFFER_SIZE;
 
	_fio.pos = pos;
 
	fseek(_fio.cur_fh, _fio.pos, SEEK_SET);
 
}
 

	
 
#if defined(LIMITED_FDS)
 
static void FioRestoreFile(int slot)
 
{
 
	/* Do we still have the file open, or should we reopen it? */
 
	if (_fio.handles[slot] == NULL) {
 
		DEBUG(misc, 6, "Restoring file '%s' in slot '%d' from disk", _fio.filenames[slot], slot);
 
		FioOpenFile(slot, _fio.filenames[slot]);
 
	}
 
	_fio.usage_count[slot]++;
 
}
 
#endif /* LIMITED_FDS */
 

	
 
/* Seek to a file and a position */
 
/**
 
 * Switch to a different file and seek to a position.
 
 * @param slot Slot number of the new file.
 
 * @param pos New absolute position in the new file.
 
 */
 
void FioSeekToFile(uint8 slot, size_t pos)
 
{
 
	FILE *f;
 
#if defined(LIMITED_FDS)
 
	/* Make sure we have this file open */
 
	FioRestoreFile(slot);
 
#endif /* LIMITED_FDS */
 
	f = _fio.handles[slot];
 
	assert(f != NULL);
 
	_fio.cur_fh = f;
 
	_fio.filename = _fio.filenames[slot];
 
	FioSeekTo(pos, SEEK_SET);
 
}
 

	
 
/**
 
 * Read a byte from the file.
 
 * @return Read byte.
 
 */
 
byte FioReadByte()
 
{
 
	if (_fio.buffer == _fio.buffer_end) {
 
		_fio.buffer = _fio.buffer_start;
 
		size_t size = fread(_fio.buffer, 1, FIO_BUFFER_SIZE, _fio.cur_fh);
 
		_fio.pos += size;
 
		_fio.buffer_end = _fio.buffer_start + size;
 

	
 
		if (size == 0) return 0;
 
	}
 
	return *_fio.buffer++;
 
}
 

	
 
/**
 
 * Skip \a n bytes ahead in the file.
 
 * @param n Number of bytes to skip reading.
 
 */
 
void FioSkipBytes(int n)
 
{
 
	for (;;) {
 
		int m = min(_fio.buffer_end - _fio.buffer, n);
 
		_fio.buffer += m;
 
		n -= m;
 
		if (n == 0) break;
 
		FioReadByte();
 
		n--;
 
	}
 
}
 

	
 
/**
 
 * Read a word (16 bits) from the file (in low endian format).
 
 * @return Read word.
 
 */
 
uint16 FioReadWord()
 
{
 
	byte b = FioReadByte();
 
	return (FioReadByte() << 8) | b;
 
}
 

	
 
/**
 
 * Read a double word (32 bits) from the file (in low endian format).
 
 * @return Read word.
 
 */
 
uint32 FioReadDword()
 
{
 
	uint b = FioReadWord();
 
	return (FioReadWord() << 16) | b;
 
}
 

	
 
/**
 
 * Read a block.
 
 * @param ptr Destination buffer.
 
 * @param size Number of bytes to read.
 
 */
 
void FioReadBlock(void *ptr, size_t size)
 
{
 
	FioSeekTo(FioGetPos(), SEEK_SET);
 
	_fio.pos += fread(ptr, 1, size, _fio.cur_fh);
 
}
 

	
 
/**
 
 * Close the file at the given slot number.
 
 * @param slot File index to close.
 
 */
 
static inline void FioCloseFile(int slot)
 
{
 
	if (_fio.handles[slot] != NULL) {
 
		fclose(_fio.handles[slot]);
 

	
 
		free(_fio.shortnames[slot]);
 
		_fio.shortnames[slot] = NULL;
 

	
 
		_fio.handles[slot] = NULL;
 
#if defined(LIMITED_FDS)
 
		_fio.open_handles--;
 
#endif /* LIMITED_FDS */
 
	}
 
}
 

	
 
/** Close all slotted open files. */
 
void FioCloseAll()
 
{
 
	for (int i = 0; i != lengthof(_fio.handles); i++) {
 
		FioCloseFile(i);
 
	}
 
}
 

	
 
#if defined(LIMITED_FDS)
 
static void FioFreeHandle()
 
{
 
	/* If we are about to open a file that will exceed the limit, close a file */
 
	if (_fio.open_handles + 1 == LIMITED_FDS) {
 
@@ -192,24 +226,29 @@ static void FioFreeHandle()
 
			if (_fio.handles[i] != NULL && _fio.usage_count[i] < count) {
 
				count = _fio.usage_count[i];
 
				slot  = i;
 
			}
 
		}
 
		assert(slot != -1);
 
		DEBUG(misc, 6, "Closing filehandler '%s' in slot '%d' because of fd-limit", _fio.filenames[slot], slot);
 
		FioCloseFile(slot);
 
	}
 
}
 
#endif /* LIMITED_FDS */
 

	
 
/**
 
 * Open a slotted file.
 
 * @param slot Index to assign.
 
 * @param filename Name of the file at the disk.
 
 */
 
void FioOpenFile(int slot, const char *filename)
 
{
 
	FILE *f;
 

	
 
#if defined(LIMITED_FDS)
 
	FioFreeHandle();
 
#endif /* LIMITED_FDS */
 
	f = FioFOpenFile(filename);
 
	if (f == NULL) usererror("Cannot open file '%s'", filename);
 
	uint32 pos = ftell(f);
 

	
 
	FioCloseFile(slot); // if file was opened before, close it
 
@@ -243,39 +282,39 @@ static const char * const _subdirs[NUM_S
 
	"ai" PATHSEP "library" PATHSEP,
 
};
 

	
 
const char *_searchpaths[NUM_SEARCHPATHS];
 
TarList _tar_list;
 
TarFileList _tar_filelist;
 

	
 
typedef std::map<std::string, std::string> TarLinkList;
 
static TarLinkList _tar_linklist; ///< List of directory links
 

	
 
/**
 
 * Check whether the given file exists
 
 * @param filename the file to try for existance
 
 * @param filename the file to try for existence.
 
 * @param subdir the subdirectory to look in
 
 * @return true if and only if the file can be opened
 
 */
 
bool FioCheckFileExists(const char *filename, Subdirectory subdir)
 
{
 
	FILE *f = FioFOpenFile(filename, "rb", subdir);
 
	if (f == NULL) return false;
 

	
 
	FioFCloseFile(f);
 
	return true;
 
}
 

	
 
/**
 
 * Test whether the fiven filename exists.
 
 * Test whether the given filename exists.
 
 * @param filename the file to test.
 
 * @return true if and only if the file exists.
 
 */
 
bool FileExists(const char *filename)
 
{
 
#if defined(WINCE)
 
	/* There is always one platform that doesn't support basic commands... */
 
	HANDLE hand = CreateFile(OTTD2FS(filename), 0, 0, NULL, OPEN_EXISTING, 0, NULL);
 
	if (hand == INVALID_HANDLE_VALUE) return 1;
 
	CloseHandle(hand);
 
	return 0;
 
#else
 
@@ -310,25 +349,25 @@ char *FioGetFullPath(char *buf, size_t b
 
 */
 
char *FioFindFullPath(char *buf, size_t buflen, Subdirectory subdir, const char *filename)
 
{
 
	Searchpath sp;
 
	assert(subdir < NUM_SUBDIRS);
 

	
 
	FOR_ALL_SEARCHPATHS(sp) {
 
		FioGetFullPath(buf, buflen, sp, subdir, filename);
 
		if (FileExists(buf)) return buf;
 
#if !defined(WIN32)
 
		/* Be, as opening files, aware that sometimes the filename
 
		 * might be in uppercase when it is in lowercase on the
 
		 * disk. Ofcourse Windows doesn't care about casing. */
 
		 * disk. Of course Windows doesn't care about casing. */
 
		if (strtolower(buf + strlen(_searchpaths[sp]) - 1) && FileExists(buf)) return buf;
 
#endif
 
	}
 

	
 
	return NULL;
 
}
 

	
 
char *FioAppendDirectory(char *buf, size_t buflen, Searchpath sp, Subdirectory subdir)
 
{
 
	assert(subdir < NUM_SUBDIRS);
 
	assert(sp < NUM_SEARCHPATHS);
 

	
 
@@ -381,35 +420,48 @@ static FILE *FioFOpenFileSp(const char *
 
		f = fopen(buf, mode);
 
	}
 
#endif
 
	if (f != NULL && filesize != NULL) {
 
		/* Find the size of the file */
 
		fseek(f, 0, SEEK_END);
 
		*filesize = ftell(f);
 
		fseek(f, 0, SEEK_SET);
 
	}
 
	return f;
 
}
 

	
 
/**
 
 * Opens a file from inside a tar archive.
 
 * @param entry The entry to open.
 
 * @param filesize [out] If not \c NULL, size of the opened file.
 
 * @return File handle of the opened file, or \c NULL if the file is not available.
 
 * @note The file is read from within the tar file, and may not return \c EOF after reading the whole file.
 
 */
 
FILE *FioFOpenFileTar(TarFileListEntry *entry, size_t *filesize)
 
{
 
	FILE *f = fopen(entry->tar_filename, "rb");
 
	if (f == NULL) return f;
 

	
 
	fseek(f, entry->position, SEEK_SET);
 
	if (filesize != NULL) *filesize = entry->size;
 
	return f;
 
}
 

	
 
/** Opens OpenTTD files somewhere in a personal or global directory */
 
/**
 
 * Opens a OpenTTD file somewhere in a personal or global directory.
 
 * @param filename Name of the file to open.
 
 * @param subdir Subdirectory to open.
 
 * @param filename Name of the file to open.
 
 * @return File handle of the opened file, or \c NULL if the file is not available.
 
 */
 
FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize)
 
{
 
	FILE *f = NULL;
 
	Searchpath sp;
 

	
 
	assert(subdir < NUM_SUBDIRS || subdir == NO_DIRECTORY);
 

	
 
	FOR_ALL_SEARCHPATHS(sp) {
 
		f = FioFOpenFileSp(filename, mode, sp, subdir, filesize);
 
		if (f != NULL || subdir == NO_DIRECTORY) break;
 
	}
 

	
 
@@ -474,25 +526,25 @@ static void FioCreateDirectory(const cha
 
	}
 

	
 
	mkdir(OTTD2FS(buf), 0755);
 
#else
 
	mkdir(OTTD2FS(name), 0755);
 
#endif
 
}
 

	
 
/**
 
 * Appends, if necessary, the path separator character to the end of the string.
 
 * It does not add the path separator to zero-sized strings.
 
 * @param buf    string to append the separator to
 
 * @param buflen the length of the buf
 
 * @param buflen the length of \a buf.
 
 * @return true iff the operation succeeded
 
 */
 
bool AppendPathSeparator(char *buf, size_t buflen)
 
{
 
	size_t s = strlen(buf);
 

	
 
	/* Length of string + path separator + '\0' */
 
	if (s != 0 && buf[s - 1] != PATHSEPCHAR) {
 
		if (s + 2 >= buflen) return false;
 

	
 
		buf[s]     = PATHSEPCHAR;
 
		buf[s + 1] = '\0';
 
@@ -517,24 +569,28 @@ char *BuildWithFullPath(const char *dir)
 

	
 
	/* Add absolute path */
 
	if (s == NULL || dest != s) {
 
		if (getcwd(dest, MAX_PATH) == NULL) *dest = '\0';
 
		AppendPathSeparator(dest, MAX_PATH);
 
		ttd_strlcat(dest, dir, MAX_PATH);
 
	}
 
	AppendPathSeparator(dest, MAX_PATH);
 

	
 
	return dest;
 
}
 

	
 
/**
 
 * Find the first directory in a tar archive.
 
 * @param tarname the name of the tar archive to look in.
 
 */
 
const char *FioTarFirstDir(const char *tarname)
 
{
 
	TarList::iterator it = _tar_list.find(tarname);
 
	if (it == _tar_list.end()) return NULL;
 
	return (*it).second.dirname;
 
}
 

	
 
static void TarAddLink(const std::string &srcParam, const std::string &destParam)
 
{
 
	std::string src = srcParam;
 
	std::string dest = destParam;
 
	/* Tar internals assume lowercase */
 
@@ -552,25 +608,25 @@ static void TarAddLink(const std::string
 
		const std::string dst_path = (dest.length() == 0 ? "" : ((*dest.rbegin() == PATHSEPCHAR) ? dest : dest + PATHSEPCHAR));
 
		_tar_linklist.insert(TarLinkList::value_type(src_path, dst_path));
 
	}
 
}
 

	
 
void FioTarAddLink(const char *src, const char *dest)
 
{
 
	TarAddLink(src, dest);
 
}
 

	
 
/**
 
 * Simplify filenames from tars.
 
 * Replace '/' by PATHSEPCHAR, and force 'name' to lowercase.
 
 * Replace '/' by #PATHSEPCHAR, and force 'name' to lowercase.
 
 * @param name Filename to process.
 
 */
 
static void SimplifyFileName(char *name)
 
{
 
	/* Force lowercase */
 
	strtolower(name);
 

	
 
	/* Tar-files always have '/' path-seperator, but we want our PATHSEPCHAR */
 
#if (PATHSEPCHAR != '/')
 
	for (char *n = name; *n != '\0'; n++) if (*n == '/') *n = PATHSEPCHAR;
 
#endif
 
}
 
@@ -1132,24 +1188,32 @@ void SanitizeFilename(char *filename)
 
	for (; *filename != '\0'; filename++) {
 
		switch (*filename) {
 
			/* The following characters are not allowed in filenames
 
			 * on at least one of the supported operating systems: */
 
			case ':': case '\\': case '*': case '?': case '/':
 
			case '<': case '>': case '|': case '"':
 
				*filename = '_';
 
				break;
 
		}
 
	}
 
}
 

	
 
/**
 
 * Load a file into memory.
 
 * @param filename Name of the file to load.
 
 * @param lenp [out] Length of loaded data.
 
 * @param maxsize Maximum size to load.
 
 * @return Pointer to new memory containing the loaded data, or \c NULL if loading failed.
 
 * @note If \a maxsize less than the length of the file, loading fails.
 
 */
 
void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
 
{
 
	FILE *in = fopen(filename, "rb");
 
	if (in == NULL) return NULL;
 

	
 
	fseek(in, 0, SEEK_END);
 
	size_t len = ftell(in);
 
	fseek(in, 0, SEEK_SET);
 
	if (len > maxsize) {
 
		fclose(in);
 
		return NULL;
 
	}
0 comments (0 inline, 0 general)