From Valve Developer Community
Revision as of 19:59, 17 April 2006 by ZeroDegrez (talk | contribs) (Search Files: grammar)
Jump to: navigation, search

Here you will find all the information you ever wanted to know about the File System in Source. How to open files, how to read files, how to create new directories and how to find a file on the local system.

My Game Directory

This does not deal specifically with the filesystem, but you might find this useful for your project.

char * pGameDir = new char[1024];
engine->GetGameDir(pGameDir, 1024);

const char *pGameDir = engine->GetGameDirectory();

Create Directory

To create a directory you need to know two things; the relative path containing the new directory name and Path ID where the path will be created — called a Path ID because it does not appear to be possible to create a directory using anything other than a search path id.

Default Path Ids

  • MOD
  • GAME
char * relpath = new char[1024];
Q_snprintf(relpath, 1024, "stuff\\%s", "newdirectory");
filesystem->CreateDirHierarchy( path, "MOD" );

This code will create a newdirectory in your stuff directory, which if does not exist will be created along with newdirectory inside of your MOD directory.

File I/O

I/O Modes

r Open a text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Open a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append to or create a text file for read/write
rb+ Open a binary file for read/write
wb+ Create a binary file for read/write
ab+ Append to or create a binary file for read/write
FileHandle_t fh;
fh = filesystem->Open( "mylog.log", "a", "MOD");

if (fh)
    filesystem->FPrintf(fh, "%s", "Logging A Test Line...");

So in this example we open mylog.log in Append mode. Then we print the line Logging A Test Line... and close the file.

Search Files

To iterate through a list of files in a given Path ID you would do the following.

FileFindHandle_t findHandle;
const char *pFilename = filesystem->FindFirstEx( "*.*", "MOD", &findHandle );
while ( pFilename != NULL )
    pFilename = filesystem->FindNext( findHandle );
filesystem->FindClose( findHandle );

*.* is the wildcard to match the files against. "MOD" is the Path ID.