2013-01-12 1 views
0
struct student 
{ 
int identity; 
char name[MAX]; 
int no_assessment; 
char assessmenttask[MAX]; 
int mark; 
}; 


void appendbfile(char filename [MAX]) 
{ 
ofstream writeb; 
char filenameb [MAX]; 
strcpy(filenameb,filename); 
student s; 

strcat(filenameb,".dat"); 

cout<<"--------------------------------" 
    <<endl 
    <<"Begin appending for binary file " 
    <<filenameb 
    <<endl 
    <<endl; 


cout<<"Enter student id: "; 
cin>>s.identity; 

cout<<"Enter student name: "; 
cin>>s.name; 

writeb.open(strcpy(filenameb,".dat"),ios::binary); 

writeb.seekp(0,ios::end); 

writeb.write (reinterpret_cast <const char *>(&s), sizeof (s)); 

writeb.close(); 

} 

프로그램을 실행할 수는 있지만 레코드가 이진 파일에 추가되는 것 같습니다. 누군가 나를 봐줄 수 있습니까?캔트가 이진 파일에 레코드를 추가합니다.

감사

열기 함수에 ios::app 플래그를 전달해야
+0

왜이 코드 조각이 작동하지 않는지 알 수 없습니다. 아마 다른 문제가 생겼을거야. –

+0

왜 오픈 콜에 strcpy가 있습니까? – perreal

+0

학생 정의를 게시 할 수 있습니까? – billz

답변

1

문제는 라인 아래에, 당신은

writeb.open(strcpy(filenameb,".dat"),ios::binary); 

을 변경해야
writeb.open(filenameb, ios::binary); 

strcat(filenameb,".dat");을 이미 작성 했으므로 strcpy는 writeb.open 안에 '.dat'을 filenameb로 복사하고 '.dat'로 파일 이름을 바꿉니다. 주의 깊게 보면 파일 '.dat'은 데이터가있는 프로그램과 동일한 디렉토리에 생성됩니다.

seekp(0,ios::end);을 호출 할 필요가 없으므로 파일 끝으로 파일 포인터를 이동하려면 기본적으로 ios::app 플래그가있는 열린 파일이 파일의 끝에 파일을 추가합니다.

writeb.open(filenameb, ios::binary | ios::app); 
writeb.write (reinterpret_cast <const char *>(&s), sizeof (s)); 
writeb.close(); 

참조 파일 열기 모드 : http://en.cppreference.com/w/cpp/io/ios_base/openmode

1

:

writeb.open(filenameb, ios::binary | ios::app); 
0

는 또한 IOS :: 응용 프로그램 OR 연산 오픈 기능에 필요합니다.

관련 문제