我之前创建了一些函数,用于读取和编写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;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以看到此代码的任何问题或有任何其他建议吗?
跳出来的最大的主要问题:
// 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);
Run Code Online (Sandbox Code Playgroud)
这会将文本创建为指向单个字符的指针,然后尝试将任意数量的字符(可能多于一个)读入其中.为了使其正常工作,您必须在确定大小之后将文本创建为字符数组,如下所示:
// 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);
Run Code Online (Sandbox Code Playgroud)
其次,您不释放分配给文本的内存.你需要这样做:
// Free the temporary storage
delete[] text;
Run Code Online (Sandbox Code Playgroud)
最后,您是否有充分的理由选择在C++中使用C文件I/O?使用C++风格的iostream可以减轻所有这些,并使您的代码更加简短,更简洁,更易读.
| 归档时间: |
|
| 查看次数: |
4451 次 |
| 最近记录: |