簡體   English   中英

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

[英]C++ fread() into a std::string

像往常一樣,指針的問題。 這次我試圖讀取一個文件(以二進制模式打開)並將其中的一部分存儲在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 );
}

這可能嗎? 我沒有得到任何消息。 我確定文件沒問題當我嘗試使用char *它確實有效但我想將它直接存儲到字符串中。 謝謝你的幫助!

首先將字符串設置得足夠大,以避免緩沖區溢出,並將字節數組作為&mystring[0]以滿足std::string const和其他要求。

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的最小調整。

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將是一個更好的選擇。 你可以在這里閱讀更多相關信息

我會建議這是做這種事情的最佳方式。 您還應該檢查以確保讀取所有字節。

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

請查看以下有關c_str的信息,以查看程序中出現的一些問題。 一些問題包括c_str不可修改,但它還返回一個指向字符串內容的指針,但是你從未初始化字符串。

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

至於解決它...你可以嘗試讀入char *然后從中初始化你的字符串。

不它不是。 std::string::c_str()方法不會返回可修改的字符序列,因為您可以從此處進行驗證。 更好的解決方案是使用緩沖區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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM