C++ fread()成为std :: string

ali*_*ali 4 c++ string casting std fread

像往常一样,指针的问题.这次我试图读取一个文件(以二进制模式打开)并将其中的一部分存储在std :: string对象中.让我们来看看:

FILE* myfile = fopen("myfile.bin", "rb");
if (myfile != NULL) {
    short stringlength = 6;
    string mystring;
    fseek(myfile , 0, SEEK_SET);
    fread((char*)mystring.c_str(), sizeof(char), (size_t)stringlength, myfile);
    cout << mystring;
    fclose(myfile );
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?我没有得到任何消息.我确定文件没问题当我尝试使用char*它确实有效但我想将它直接存储到字符串中.谢谢你的帮助!

Pot*_*ter 8

首先将字符串设置得足够大以避免缓冲区溢出,并访问字节数组&mystring[0]以满足const其他要求std::string.

FILE* myfile = fopen("myfile.bin", "rb");
if (myfile != NULL) {
    short stringlength = 6;
    string mystring( stringlength, '\0' );
    fseek(myfile , 0, SEEK_SET);
    fread(&mystring[0], sizeof(char), (size_t)stringlength, myfile);
    cout << mystring;
    fclose(myfile );
}
Run Code Online (Sandbox Code Playgroud)

此代码中存在许多问题,但这是对正确使用的最小调整std::string.


小智 6

我会推荐这是做这种事情的最佳方式。您还应该检查以确保读取了所有字节。

    FILE* sFile = fopen(this->file.c_str(), "r");

    // if unable to open file
    if (sFile == nullptr)
    {
        return false;
    }

    // seek to end of file
    fseek(sFile, 0, SEEK_END);

    // get current file position which is end from seek
    size_t size = ftell(sFile);

    std::string ss;

    // allocate string space and set length
    ss.resize(size);

    // go back to beginning of file for read
    rewind(sFile);

    // read 1*size bytes from sfile into ss
    fread(&ss[0], 1, size, sFile);

    // close the file
    fclose(sFile);
Run Code Online (Sandbox Code Playgroud)