今天运行一个例程,是一个文件文件里读出数据,然后写入一数据文件中。读入的数据格式如下:
课程表
CourseID CourseName Time Credit
0101 computerPrinciple 86 5
0102 Programming 72 4
源程序如下 :
#include <iostream>
#include<fstream>
using namespace std;
struct course{
char num[5];
int hour;
int credit;
};
void createBinaryFile( char * filetxt, char * filedat){
char strBuf[80]= { 0 };
char strBuf2[80] = {0};
char ID[4] = {0};
char name[25] = {0 };
int rdHour;
int rdCredit;
course aCourse;
ofstream fout(filedat, ios::out);
if(!fout){
cerr<<"D:\\courseFile.dat can not be opened!";
exit (1);
}
ifstream fin(filetxt, ios::in);
if(!fin) {
cerr<<"D:\\courseFile2.txt can not be opened!";
exit (1);
}
fin.getline(strBuf,80);
fin.getline(strBuf2,80);
while(!fin.eof()){
fin>>ID>>name>>rdHour>>rdCredit;
aCourse.hour = rdHour;
aCourse.credit = rdCredit;
int i = 0;
while(ID[i]) {
aCourse.num[i] = ID[i];
++i;
}
aCourse.num[i] = '\0';
fout.write(reinterpret_cast<const char *>(&aCourse),sizeof(course));
}
}
void main(){
createBinaryFile("D:\\courseFile2.txt", "D:\\courseFile.dat");
}
编译无问题,但运行时出现错误:
Run-Time Check Failure #2 - Stack around the variable 'ID' was corrupted.
经过调试发现,在定义变量时有问题,原来的定义为:
char ID[4];
ID所代表的课程号本身就有4个字符,加要上一个表示结束的‘\0'字符,长度应该定义为5. 否则在将ID[]数组逐字符copy给aCourse.num时,没有结束符就会出现错误。
所以,注意在定义字符数组时,长度一定设定为要包含的字符个数再加1.