Ste*_*cob 1 c++ file-io fstream
我正在尝试学习动态文件访问.我的代码如下:
int main()
{
dtbrec xrec; // class object
fstream flh;
// Doesn't create a new file unless ios::trunc is also given.
flh.open("database.txt", ios::in | ios::out | ios::binary);
flh.seekp(0,ios::end);
xrec.getdata();
flh.write((char*)&xrec, sizeof(dtbrec));
flh.close();
}
Run Code Online (Sandbox Code Playgroud)
我认为fstream
默认情况下会创建一个新文件'database.txt'(如果它不存在).关于什么可能是错的任何想法?
Ste*_*cob 11
关于fstream的一些指示:
一个.如果使用反斜杠指定目录,例如使用fstream f时;
f.open("folder\file",ios :: out);
它不起作用,反斜杠必须以反斜杠开头,所以正确的方法是:
f.open("folder \\ file",ios :: out);
湾 如果要创建新文件,则无效:
f.open("file.txt",ios :: in | ios :: out | ios :: binary);
正确的方法是首先使用ios :: out或ios :: trunc创建文件
f.open("file.txt".io :: out)或f.open("file.txt",ios :: trunc);
然后
f.open("file.txt",ios :: in | ios :: out | ios :: binary);
C.最后,它可以按照此答案中指定的顺序, fstream不创建文件
基本上ios :: in要求已经有一个现有文件.