I'm trying to load several files into memory (small files), but the problem is that when I try to load another file soon then all files have the same name as the last file loaded.
I'm using a struct
that contains name, size of the name, data and size of the data, to represent the files.
// Cabeçalho
struct AssetHeader
{
char* version;
long version_sz;
int files_num;
};
// Estrutura para representar os arquivos
struct AssetData
{
char* name;
char* data;
long name_sz;
long data_sz;
};
class AssetManager
{
protected:
FILE* m_pFile;
AssetHeader* m_pHeader;
std::vector<AssetData*> m_pAssets;
unsigned int m_FileNum;
.....
.....
public:
inline std::vector<AssetData*> getFileList() {return m_pAssets;}
inline int getFileCount() {return (int)m_FileNum;}
AssetData* getFileByName(std::string name);
void createAsset(const char* name="DefaultAssetName.asset");
void loadAsset(const char* filename);
void addFile(const char* filename);
void saveFile(AssetData* asset, const char* filename);
void clear();
void writeAsset();
void closeAsset();
protected:
void writeAssetHeader();
void writeAssetBlock(AssetData* asset);
void readAssetHeader();
void readAssetBlock();
};
// Carrega um arquivo na memória
void AssetManager::addFile(const char* filename)
{
AssetData* asset = new AssetData();
FILE* file = fopen(filename, "rb");
fseek(file, 0, SEEK_END);
asset->data_sz = ftell(file);
fseek(file, 0, SEEK_SET);
asset->data = new char[asset->data_sz];
if(fread(&asset->data[0], sizeof(char), asset->data_sz, file) == 0) {
delete asset;
asset = NULL;
fclose(file);
}
fclose(file);
asset->name_sz = strlen(filename);
asset->name = (char*)filename;
m_FileNum += 1;
m_pAssets.push_back(asset);
m_pHeader->files_num = m_FileNum;
}
// Utilização
int main(int argc, char* argv[])
{
AssetManager* asset_mgr = new AssetManager();
asset_mgr->createAsset("asset.txt");
std::string name;
name = "1.txt";
asset_mgr->addFile(name.c_str());
name = "2.txt";
asset_mgr->addFile(name.c_str());
asset_mgr->writeAsset();
asset_mgr->closeAsset();
return 0;
}
I do not know what I'm doing wrong. I did a test using a print
in each HAssetData
stored but the problem is how I was told, the files get the name of the last file loaded.