源代码文件结构如下,欲打开在项目目录下即main.cpp同级目录下的stud.dat文件,直接写文件名报错,打开失败!
仔细检查发现,C++中的当前目录不是指的当前源文件所在目录,而是编译后的exe文件所在的cmake-build-debug目录,这个目录才是当前目录。所以相对路径需要用以下写法才可以正确打开文件:
#include <iostream>
#include <fstream>
using namespace std;
struct Student{
int num;
char name[20];
float score;
};
int main() {
Student stud[5]={1001,"Li",85,1002,"Fang",97.5,1004,"Wang",54,1006,"Tan",76.5,1010,"Ling",96};
fstream iofile("..\\stud.dat",ios::in|ios::out|ios::binary);
cout << !iofile << endl;
if(!iofile){
cerr<<"open error!"<<endl;
abort();
}
for (int i = 0; i < 5; i++) {
iofile.write((char*)&stud[i],sizeof(stud[i]));
}
iofile.close();
return 0;
}