Reputation: 317
I have to store the name of a file into a binary file that I am writing, I currently have written it like this:
void write(map<char, bits> &bitstring,map<char,int> &ccount, string header,string fname,ofstream &outf)
{
ifstream inf(header+fname);
cout << "FName: " << fname << endl;
const char * pName = fname.c_str();
fname = header+ fname + ".mcp";
const char * c = fname.c_str();
FILE* pFile;
pFile = fopen(c, "w+b");
inf.seekg(ios::beg, ios::end);
int size = inf.tellg();
int length = 0;
string data = "";
int magicNum = 2262;
int fileNameSize = strlen(pName);
fwrite(&fileNameSize, sizeof(int), 1, pFile);
cout <<"FIle Name Size: "<< fileNameSize << endl;
fwrite(pName, fileNameSize, 1, pFile);
fclose(pFile);
}
And I also send the size of the file name, so that I know how much data I need to read to get the whole file name.
void read2(string fname, map<char, int> &charCounts, std::vector<bool> &bits,ofstream &outf)
{
string fname1 = fname + ".mcp", outfile = "binarycheck";
bool testDone = false, counts = false;
std::ifstream inf(fname1, std::ios::binary);
std::ofstream ouf("binarycheck.txt", std::ios::binary);
char character;
int count[1] = { 0 };
int checkcount = 0;
int mNum[1] = { 0 }, size[1] = { 0 };
int FNamesize = 0;
inf.read((char*)&FNamesize, sizeof(int));
char *name=new char[FNamesize+1];
inf.read(name, FNamesize);
name[FNamesize] = '\0';
string str(name);
cout << "File Name: ";
cout << std::string(name) << endl;
cout << "Magic Num: " << mNum[0] << endl;
cout << "File Name Size: " << FNamesize<< endl;
inf.close();
}
I get the Size correctly, but I have no idea how to iterate through name in order to save it back as a string. I tried using a vector but it didn't really help since inf.read uses a char* as its first parameter. Any help would be great.
Upvotes: 4
Views: 1198
Reputation: 317
Well, in a fluke accident I ended up solving my own issue. For some reason when I declared
FILE* pFile;
pFile = fopen(c, "w+b");
Before the declaration of
const char * pName = fname.c_str();
The call corrupted the value of pName before it was written to the file, which is what caused the errors. Problem solved!
Upvotes: 3
Reputation: 2182
Seeing as you're using ifstream, why not also use ofstream? Then it would just be ofs << filename
to store and ifs >> filename
to read where filename
is a string. No need to faff around with the length yourself.
Upvotes: 0