【问题标题】:Reading a char* from a binary file从二进制文件中读取 char*
【发布时间】:2014-10-15 08:07:52
【问题描述】:

我必须将文件名存储到我正在编写的二进制文件中,我目前是这样写的:

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);

}

我还发送了文件名的大小,这样我就知道需要读取多少数据才能获得整个文件名。

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();
}

我正确获取了 Size,但我不知道如何遍历 name 以便将其保存为字符串。我尝试使用向量,但它并没有真正帮助,因为 inf.read 使用 char* 作为它的第一个参数。 任何帮助都会很棒。

【问题讨论】:

  • 问题是fname = header + fname + ".mcp"; 使pName 失效,它变成了一个悬空指针,任何使用它都会导致未定义的行为。
  • 这正是@molbdnilo 解决的问题,现在效果很好。感谢您的帮助:D

标签: c++ binary char ifstream


【解决方案1】:

好吧,在一次偶然的事故中,我最终解决了自己的问题。出于某种原因,当我宣布

FILE* pFile;
pFile = fopen(c, "w+b"); 

声明之前

const char * pName = fname.c_str();

调用在 pName 写入文件之前损坏了它的值,这是导致错误的原因。问题解决了!

【讨论】:

    【解决方案2】:

    既然您正在使用 ifstream,为什么不也使用 ofstream?那么它就是ofs &lt;&lt; filename 来存储和ifs &gt;&gt; filename 来读取filename 是一个字符串的位置。无需自己纠结长度。

    【讨论】:

    • 我使用 fwrite 而不是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多