2011-02-23 5 views
0

전체 입력 파일을 문자열로 읽으려고합니다. 지금은이 :파일을 동적 문자열 배열로 복사하는 방법

pBuff이 DynString라는 동적 String 객체 인
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); 
} 

나는 임시 DynString 객체를 생성 할 일은해야하고 다음 내의 readLine를 사용, 임시의 역할이 어떻게 생각 메서드를 사용하여 텍스트 문자열의 한 줄에 임시 문자열을 할당합니다. 한 번 완료되면 이전 문자열 배열 "pBuff"을 삭제 한 다음 temp를 새 pBuff 배열에 복사합니다.

concatenate 함수를 사용해야합니까? temp 배열의 요소를 기존 pBuff에 추가하면됩니까?

죄송합니다. 혼란 스럽다면 헤더 파일에 다른 방법이 있지만 포함하기가 너무 어렵습니다.

+0

파일 내용이 pBuff에 저장되어 있습니까? 어쩌면 머리글 만 제공하면 수업이 어떻게 작동하는지 이해하는 데 도움이됩니다. – RedX

답변

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

관련 문제