Close file pointers immediately after reading/writing

This commit is contained in:
MysterD 2022-06-04 17:33:45 -07:00
parent b84645b4d1
commit 084ba327fd
3 changed files with 39 additions and 17 deletions

View File

@ -222,18 +222,28 @@ struct BassAudio* audio_load_internal(const char* filename, bool isStream) {
// remember file
bassAudio->file = modFile;
// copy audio into rawData
// open file pointer
bool opened = false;
if (modFile->fp == NULL) {
modFile->fp = fopen(modFile->cachedPath, "rb");
if (modFile->fp == NULL) {
LOG_ERROR("Could not open mod file: %s", modFile->cachedPath);
return NULL;
}
opened = true;
}
// copy data
rewind(modFile->fp);
bassAudio->rawData = (char*)malloc(modFile->size * sizeof(char));
fread(bassAudio->rawData, modFile->size, 1, modFile->fp);
// close file pointer
if (opened) {
fclose(modFile->fp);
modFile->fp = NULL;
}
// load audio and return it
if (isStream) {
bassAudio->handle = bassh_create_fx_stream_from_file(bassAudio->rawData, modFile->size, 0);

View File

@ -71,22 +71,6 @@ void mods_activate(struct Mods* mods) {
}
}
// open file pointers
if (mods != &gRemoteMods) {
for (int i = 0; i < gActiveMods.entryCount; i++) {
struct Mod* mod = gActiveMods.entries[i];
for (int j = 0; j < mod->fileCount; j++) {
struct ModFile* file = &mod->files[j];
file->fp = fopen(file->cachedPath, "rb");
if (file->fp == NULL) {
LOG_ERROR("Failed to open file '%s'", file->cachedPath);
continue;
}
}
}
}
mod_cache_save();
}

View File

@ -265,10 +265,27 @@ void network_send_download(u64 requestOffset) {
u64 fileReadOffset = MAX(((s64)requestOffset - (s64)fileStartOffset), 0);
u64 fileReadLength = MIN((modFile->size - fileReadOffset), (CHUNK_SIZE - chunkFill));
// open file pointer
bool opened = false;
if (modFile->fp == NULL) {
modFile->fp = fopen(modFile->cachedPath, "rb");
if (modFile->fp == NULL) {
LOG_ERROR("Failed to open mod file during download: %s", modFile->cachedPath);
return;
}
opened = true;
}
// read from file, filling chunk
fseek(modFile->fp, fileReadOffset, SEEK_SET);
fread(&chunk[chunkFill], sizeof(u8), fileReadLength, modFile->fp);
// close file pointer
if (opened) {
fclose(modFile->fp);
modFile->fp = NULL;
}
// increment counters
chunkFill += fileReadLength;
fileStartOffset += modFile->size;
@ -384,8 +401,19 @@ after_group:;
// read from file, filling chunk
if (!modFile->cachedPath) {
open_mod_file(mod, modFile);
if (modFile->fp == NULL) {
LOG_ERROR("Failed to open file for download write: %s", modFile->cachedPath);
return;
}
fseek(modFile->fp, fileWriteOffset, SEEK_SET);
fwrite(&chunk[chunkPour], sizeof(u8), fileWriteLength, modFile->fp);
if (modFile->fp != NULL) {
fflush(modFile->fp);
fclose(modFile->fp);
modFile->fp = NULL;
}
wroteBytes += fileWriteLength;
}