2009-05-03 2 views
0

파일의 일부를 이진 모드로 바꾸는 데 문제가 있습니다. 어떤 이유로 내 seekp() 줄이 파일 포인터를 원하는 위치에 놓지 않습니다. 지금은 원하는 부분을 대체하는 대신 파일의 끝에 새 내용을 추가합니다.이진 모드에서 파일의 일부를 바꾸는 데 seekp() 문제가 발생했습니다.

long int pos; 
bool found = false; 
fstream file(fileName, ios::binary|ios::out|ios::in); 

file.read(reinterpret_cast<char *>(&record), sizeof(Person)); 

while (!file.eof()) 
{ 
    if (record.getNumber() == number) { 
     pos=file.tellg(); 
     found = true; 
     break; 
} 

// the record object is updated here 

file.seekp(pos, ios::beg); //this is not placing the file pointer at the desired place 
file.write(reinterpret_cast<const char *>(&record), sizeof(Person)); 
cout << "Record updated." << endl; 
file.close(); 

내가 잘못하고 있나?

미리 감사드립니다.

답변

1

while() 루프가 작동하는 방식이 표시되지 않습니다. 일반적으로 eof()를 테스트하지 말고 대신 읽기 작업이 제대로 수행되었는지 테스트해야합니다. 당신은`숫자도 기록을 갱신하지 - - 그래서 기본적으로 당신이 가서 여기

#include <iostream> 
#include <fstream> 
using namespace std; 

struct P { 
    int n; 
}; 

int main() { 
    fstream file("afile.dat" , ios::binary|ios::out|ios::in); 
    P p; 
    p.n = 1; 
    file.write((char*)&p, sizeof(p)); 
    p.n = 2; 
    int pos = 0; 
    file.seekp(pos, ios::beg); 
    file.write((char*)&p, sizeof(p)); 
} 
0
while (!file.eof()) 
{ 
    if (record.getNumber() == number) { 
     pos=file.tellg(); 
     found = true; 
     break; 
} 

:

다음 코드를 덮어 다음 (존재해야합니다) 파일에 레코드를 기록하고 모든 파일을 통해하는 것은 "일부"위치에 쓰기 (POS가 inited는하지 않음)

그리고 닐 버터 워스 바로 당신이 떨어지게

를 생략 등) (전 8을 입력하는 동안 게시) 보인다
관련 문제