2011-02-23 93 views
0

我試圖將整個輸入文件讀入到字符串中。現在,我有:如何將文件複製到動態字符串數組

bool DynString::readLine(std::istream& in) 
{ 
    if(in.eof()) 
    { 
     *this = DynString(); // Default string value. 
     return(false); 
    } 

    char s[1001]; 
    in.getline(s, 1001); 

    // Delete old string-value and create new pBuff string with copy of s 
    delete [] pBuff; 

    pBuff = new char[strlen(s) + 1]; 
    DynString pBuff(s); 

    return(true); 
} 

bool DynString::readFile(const char filename[]) 
{ 
    std::ifstream in(filename); 
    if(! in.is_open()) 
    { 
     *this = DynString(); // Default string value. 
     return(false); 
    } 

    // Delete old string-value and 
    // Read the file-contents into a new pBuff string 

    delete [] pBuff; 

    DynString tempString; 
    return(true); 
} 

凡PBUFF一個名爲DynString動態String對象

我想我要做的就是創建一個臨時DynString對象,並把它作爲一個臨時的,然後使用ReadLine方法將臨時字符串分配給文本文件的一行。一旦完成,我會刪除舊的字符串數組「pBuff」,然後將temp複製到一個新的pBuff數組中。

這是否需要使用concatonate函數,我只需要將temp數組中的元素添加到現有的pBuff中?

對不起,如果這是有點令人困惑,它在頭文件中有其他方法,但它包括太多。

+0

是否將文件的內容存儲在pBuff中?也許只提供標題可以幫助我們理解班級應該如何工作。 – RedX 2011-02-23 08:39:12

回答

0

爲什麼不像以下那樣簡單一些,還是你必須使用DynString類?

static std::string readFile(const std::string& sFile) 
{ 
    // open file with appropriate flags 
    std::ifstream in1(sFile.c_str(), std::ios_base::in | std::ios_base::binary); 
    if (in1.is_open()) 
    { 
    // get length of file: 
    in1.seekg (0, std::ios::end); 
    std::streamoff length = in1.tellg(); 
    in1.seekg (0, std::ios::beg); 
    // Just in case 
    assert(length < UINT32_MAX); 
    unsigned uiSize = static_cast<unsigned>(length); 
    char* szBuffer = new char[uiSize]; 
    // read data as a block: 
    in1.read (szBuffer, length); 
    in1.close(); 

    std::string sFileContent(szBuffer, uiSize); 
    delete[] szBuffer; 
    return sFileContent; 
    } 
    else 
    { 
    // handle error 
    } 
} 
+0

我必須使用DynString類 – Connor 2011-02-23 04:52:05

相關問題