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

时间:2012-11-28 18:52:33

标签: 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 );
}

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

5 个答案:

答案 0 :(得分:6)

首先将字符串设置得足够大,以避免缓冲区溢出,并将字节数组作为&mystring[0]访问,以满足conststd::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 );
}

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

答案 1 :(得分:3)

string::c_str()会返回您无法修改的const char*

执行此操作的一种方法是首先使用char *并从中构造一个字符串。

实施例

char buffer = malloc(stringlength * sizeof(char));
fread(buffer, sizeof(char), (size_t)stringlength, myfile);
string mystring(buffer);
free(buffer);

但话说回来,如果你想要一个字符串,你或许应该问问自己Why am I using fopen and fread in the first place??

fstream将是一个更好的选择。 您可以阅读更多相关信息here

答案 2 :(得分:2)

我会建议这是做这种事情的最好方法。此外,您应该检查以确保读取所有字节。

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

答案 3 :(得分:1)

请查看以下有关c_str的内容,以了解您的程序出现的一些问题。一些问题包括c_str不可修改,但它还返回一个指向字符串内容的指针,但你从未初始化字符串。

http://www.cplusplus.com/reference/string/string/c_str/

至于解决它...你可以尝试读入char *然后从中初始化你的字符串。

答案 4 :(得分:1)

不,不是。 std::string::c_str()方法不会返回可修改的字符序列,因为您可以从here进行验证。更好的解决方案是使用缓冲区char数组。这是一个例子:

FILE* myfile = fopen("myfile.bin", "rb");
    if (myfile != NULL) {
        char buffer[7]; //Or you can use malloc() / new instead.  
        short stringlength = 6;
        fseek(myfile , 0, SEEK_SET);
        fread(buffer, sizeof(char), (size_t)stringlength, myfile);
        string mystring(buffer);
        cout << mystring;
        fclose(myfile );
        //use free() or delete if buffer is allocated dynamically
}