简体   繁体   English

c ++使用fstream从二进制文件中读取字符串

[英]c++ Reading string from binary file using fstream

I am trying to read a string from a binary file but cant seem to get it to work.我正在尝试从二进制文件中读取一个字符串,但似乎无法让它工作。 I am a pretty new to c++.我是 C++ 的新手。 Can anybody help please?有人可以帮忙吗? Thanks.谢谢。

string Name = "Shaun";
unsigned short int StringLength = 0;

int main()
{
    StringLength = Name.size();

    ofstream oFile("File.txt", ios::binary|ios::out);
    oFile.write((char*)&StringLength, sizeof(unsigned short int));
    oFile.write(Name.c_str(), StringLength);
    oFile.close();

    StringLength = 0;
    Name = "NoName";

    ifstream iFile("File.txt", ios::binary|ios::in);
    if(!iFile.is_open())
        cout << "Failed" << endl;
    else
    {
        iFile.read((char *)&StringLength, sizeof(unsigned short int));
        iFile.read((char *)&Name, StringLength);
    }

    cout << StringLength << " " << Name << endl;

    system("Pause>NUL");
    return 0;
}

This is the problematic line.这是有问题的线路。

    iFile.read((char *)&Name, StringLength);

You are reading the char* part of a std::string directly into the memory of Name .您正在将std::stringchar*部分直接读入Name的内存中。

You need to save both the size of the string as well as the string so that when you read the data, you would know how much memory you need to read the data.您需要保存字符串和字符串的大小,以便在读取数据时知道读取数据需要多少内存。

Instead of代替

oFile.write(Name.c_str(), StringLength);

You would need:你需要:

size_t len = Name.size();
oFile.write(&len, sizeof(size_t));
oFile.write(Name.c_str(), len);

On the way back, you would need:在回来的路上,你需要:

iFile.read(&len, sizeof(size_t));
char* temp = new char[len+1];
iFile.read(temp, len);
temp[len] = '\0';
Name = temp;
delete [] temp;

you need to create a buffer of char type.您需要创建一个 char 类型的缓冲区。

char *buffer = new char[size];

Then use your buffer as the parameter to read function然后使用您的缓冲区作为参数来读取函数

iFile.read(buffer, size);

Instead of this而不是这个

iFile.read((char *)&Name, StringLength);

Try this:尝试这个:

Name.resize(StringLength);
iFile.read((char *)&Name[0], StringLength);

Your original line overwrites the string object data from the beginning, which may contain the string length and capacity, for instance, instead of the character data.您的原始行从头开始覆盖字符串对象数据,例如,它可能包含字符串长度和容量,而不是字符数据。 Also you don't resize the string appropriately to be able to contain the data.此外,您没有适当地调整字符串的大小以包含数据。

Conceptually, you need to understand the data stream which you are reading.从概念上讲,您需要了解您正在阅读的数据流。 Not everything use ASCII which uses a byte size of 8 bits.并非所有东西都使用 ASCII,它使用 8 位的字节大小。 I also notice you did not set bit size read which can be as little as one bit to as large as {R, B, G, A} color set.我还注意到您没有设置读取位大小,它可以小到一位,大到 {R, B, G, A} 颜色集。 Using your basic 2 dimensional reiteration structured code.使用您的基本二维重复结构化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM