2010-12-07 5 views
6

전체 file.txt를 char 배열로 읽으려고합니다. 그러나 몇 가지 문제, 제안하십시오 =]텍스트 파일을 char 배열로 읽어들입니다. C++ ifstream

ifstream infile; 
infile.open("file.txt"); 

char getdata[10000] 
while (!infile.eof()){ 
    infile.getline(getdata,sizeof(infile)); 
    // if i cout here it looks fine 
    //cout << getdata << endl; 
} 

//but this outputs the last half of the file + trash 
for (int i=0; i<10000; i++){ 
    cout << getdata[i] 
} 
+0

아니면 누군가가 문자 배열에 텍스트 파일을 저장하는 더 좋은 방법을 제안 할 수 있습니다. – nubme

+0

장난감 앱 이외에는 이렇게하면 무제한 메모리 할당을 막을 수 있습니다. – seand

+2

세미콜론이 누락 된 것 같습니다. –

답변

1

새로운 라인을 읽을 때마다있는 것은 당신이 이전을 덮어 씁니다. 인덱스 변수 i를 유지하고 infile.read(getdata+i,1)을 사용하고 i를 증가시킵니다.

+0

고마워요. =] – nubme

+2

'read (..., 1)'는 한 번에 한 문자 씩 읽습니다 ... 매우 비효율적입니다. –

+0

infile.seekg (0, ios :: end); infile.seekg (0, ios :: beg); infile.read (getdata, len); – tmiddlet

2

전체 파일을 버퍼에 빨아 들일 계획이라면 한 줄씩 읽을 필요가 없습니다.

char getdata[10000]; 
infile.read(getdata, sizeof getdata); 
if (infile.eof()) 
{ 
    // got the whole file... 
    size_t bytes_really_read = infile.gcount(); 

} 
else if (infile.fail()) 
{ 
    // some other error... 
} 
else 
{ 
    // getdata must be full, but the file is larger... 

} 
+0

파일이'10000' 문자보다 큰 경우 어떻게합니까? – Nawaz

+0

@ Nawaz는 else 절이 될 것입니다 ... –

+0

.... 그리고 거기에서 무엇을 할 것입니까? 더 큰 크기의 다른 문자 배열을 선언하고 다시 읽으십시오? 틀렸어, 그렇지? – Nawaz

2
std::ifstream infile; 
infile.open("Textfile.txt", std::ios::binary); 
infile.seekg(0, std::ios::end); 
size_t file_size_in_byte = infile.tellg(); 
std::vector<char> data; // used to store text data 
data.resize(file_size_in_byte); 
infile.seekg(0, std::ios::beg); 
infile.read(&data[0], file_size_in_byte); 
3

사용 std::string :

std::string contents; 

contents.assign(std::istreambuf_iterator<char>(infile), 
       std::istreambuf_iterator<char>()); 
+0

... 항상이 마법을 암기하는 데 어려움이있었습니다. 아주 직관적이지 않습니다. PS. OP가 char 배열을 요청했기 때문에,'contents.c_str()'이 유용 할 수 있습니다. – gluk47

관련 문제