从二进制文件中读取std :: string

时间:2009-08-11 20:26:22

标签: c++

我之前创建了一些函数,用于读取和编写std :: strings到FILE *,以便在二进制模式下读取。它们之前工作正常(并且WriteString()仍然有效)但ReadString()在运行时不断给出内存损坏错误。通过在字符串数据之前将其大小写为unsigned int作为char来存储字符串。

bool WriteString(std::string t_str, FILE* t_fp) {
// Does the file stream exist and is it valid? If not, return false.
if (t_fp == NULL) return false;
// Create char pointer from string.
char* text = const_cast<char*>(t_str.c_str());
// Find the length of the string.
unsigned int size = t_str.size();
// Write the string's size to the file.
fwrite(&size, sizeof(unsigned int), 1, t_fp);
// Followed by the string itself.
fwrite(text, 1, size, t_fp);
// Everything worked, so return true.
return true;

}



std::string ReadString(FILE* t_fp) {
// Does the file stream exist and is it valid? If not, return false.
if (t_fp == NULL) return false;
// Create new string object to store the retrieved text and to return to the calling function.
std::string str;
// Create a char pointer for temporary storage.
char* text = new char;
// UInt for storing the string's size.
unsigned int size;
// Read the size of the string from the file and store it in size.
fread(&size, sizeof(unsigned int), 1, t_fp);
// Read [size] number of characters from the string and store them in text.
fread(text, 1, size, t_fp);
// Store the contents of text in str.
str = text;
// Resize str to match the size else we get extra cruft (line endings methinks).
str.resize(size);
// Finally, return the string to the calling function.
return str;

}

任何人都可以看到此代码有任何问题或有任何其他建议吗?

3 个答案:

答案 0 :(得分:5)

跳出来的最大的主要问题是:

// Create a char pointer for temporary storage.
char* text = new char;
// ...
// Read [size] number of characters from the string and store them in text.
fread(text, 1, size, t_fp);

这会将文本创建为指向单个字符的指针,然后尝试将任意数量的字符(可能多于一个)读入其中。为了使其正常工作,您必须在弄清楚大小是什么之后将文本创建为数组,如下所示:

// UInt for storing the string's size.
unsigned int size;
// Read the size of the string from the file and store it in size.
fread(&size, sizeof(unsigned int), 1, t_fp);
// Create a char pointer for temporary storage.
char* text = new char[size];
// Read [size] number of characters from the string and store them in text.
fread(text, 1, size, t_fp);

其次,您不释放分配给文本的内存。你需要这样做:

// Free the temporary storage
delete[] text;

最后,您是否有充分的理由选择在C ++中使用C文件I / O?使用C ++风格的iostream可以减轻所有这些,并使您的代码更加简短,更简洁,更易读。

答案 1 :(得分:2)

问题是:

char* text = new char;

你要分配一个角色。知道size后进行分配,并分配所需的所有size个字符(例如new char[size])。 (为了避免泄漏,当然在复制之后将其删除)。

答案 2 :(得分:0)

我很抱歉,但所选择的答案对我不起作用。

// UInt for storing the string's size.
unsigned int size;
// Read the size of the string from the file and store it in size.
fread(&size, sizeof(unsigned int), 1, t_fp);
// Create a char pointer for temporary storage.
char* text = new char[size];
// Read [size] number of characters from the string and store them in text.
fread(text, 1, size, t_fp);

大小最终是一个非常大的数字。我错过了什么吗?