Developer Guide (Version 1.11)

Writing to File System Files With CryPak

Writing a file is similar to the process for reading one. To write to files, you use CCryFile::Write, which always writes to the file system and never to .pak archives. For information on writing files to archive files, see Modifying Paks With CryArchive.

  1. Type the following, which contains the if-else statement that frames the code for writing to a file. The WriteToExampleFile() function write will write the contents of the file and return true if it succeeds, and false if not.

    char* newContent = "File has been modified"; bool appendToFile = false;  if (!WriteToExampleFile(newContent, strlen(newContent), appendToFile)) {  CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "WriteToExampleFile() failed"); }  else { CryLogAlways("Text has been written to file, %s", newContent); }
    • WriteToExampleFile() takes the following three parameters:

      • newContent - The text which will be written to ExampleText.txt on the file system.

      • strlen(newContent) - Returns size of newContent, which is the number of bytes to be written.

      • appendToFile - true if newContent will be added to the already existing content; false if the file will be overwritten.

  2. Type the following for the WriteToExampleFile) function.

    bool WriteToExampleFile(char* text, int bytes, bool appendToFile) { CCryFile file; const char* filename = "examples/exampletext.txt"; assert(bytes > 0); char* mode = NULL; if (appendToFile) mode = "a"; else mode = "w"; char str[1024]; if (!file.Open(filename, mode)) { sprintf(str, "Can't open file, (%s)", filename); CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "%s", str); return false; } [...] file.Close(); return true; }
    • mode specifies if the text is to be appended to the existing file or if it will overwrite existing file contents. "w" means 'write' to a clean file, and "a" means 'append' to the existing file.

  3. The final step writes the text to the file and returns the number of bytes written, or an error message if none were written.

    int bytesWritten = file.Write(text, bytes); assert(bytesWritten == bytes); if (bytesWritten == 0) { sprintf(str, "Can't write to file, (%s)", filename); CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "%s", str); return false; }
    • bytesWritten tells how many bytes were written by calling the Write() function.