FILE * FileCache::Save(const TCHAR *name, const TCHAR *original_path) { FileInfo original_info; if (!GetRegularFileInfo(original_path, original_info)) return NULL; Directory::Create(cache_path); TCHAR path[PathBufferSize(name)]; MakeCachePath(path, name); File::Delete(path); FILE *file = _tfopen(path, _T("wb")); if (file == NULL) return NULL; if (fwrite(&FILE_CACHE_MAGIC, sizeof(FILE_CACHE_MAGIC), 1, file) != 1 || fwrite(&original_info, sizeof(original_info), 1, file) != 1) { fclose(file); File::Delete(path); return NULL; } return file; }
FILE * FileCache::Save(const TCHAR *name, Path original_path) { FileInfo original_info; if (!GetRegularFileInfo(original_path, original_info)) return nullptr; Directory::Create(cache_path); const auto path = MakeCachePath(name); File::Delete(path); FILE *file = _tfopen(path.c_str(), _T("wb")); if (file == nullptr) return nullptr; if (fwrite(&FILE_CACHE_MAGIC, sizeof(FILE_CACHE_MAGIC), 1, file) != 1 || fwrite(&original_info, sizeof(original_info), 1, file) != 1) { fclose(file); File::Delete(path); return nullptr; } return file; }
FILE * FileCache::Load(const TCHAR *name, const TCHAR *original_path) { FileInfo original_info; if (!GetRegularFileInfo(original_path, original_info)) return NULL; TCHAR path[PathBufferSize(name)]; MakeCachePath(path, name); FileInfo cached_info; if (!GetRegularFileInfo(path, cached_info)) return NULL; /* if the original file is newer than the cache, discard the cache - unless the system clock is skewed (origina file's modification time is in the future) */ if (original_info.mtime > cached_info.mtime && !original_info.IsFuture()) { File::Delete(path); return NULL; } FILE *file = _tfopen(path, _T("rb")); if (file == NULL) return NULL; unsigned magic; struct FileInfo old_info; if (fread(&magic, sizeof(magic), 1, file) != 1 || magic != FILE_CACHE_MAGIC || fread(&old_info, sizeof(old_info), 1, file) != 1 || old_info != original_info) { fclose(file); File::Delete(path); return NULL; } return file; }