fstream 只是不会创建文件
您好,我正在尝试使用 fstream 文件句柄执行以下操作:
- 写入文件
- 从文件读取
- 创建文件(如果不存在)
问题: 由于某种原因,我无法创建该文件。
filepath= name + "/mails.txt";
mkdir(name.c_str(),0600);
log.open(filepath.c_str(), ios::in|ios::out|ios::ate);
if(!log.is_open())cout<<"error"<<endl;
log<<flush;
如果文件存在,它就会完成他的工作,但是当文件不存在时,它就不会。
编辑:因为我严重未能在评论中发布代码,所以我在这里尝试一下:D
user::user(string aaa)
{
string filepath;
name=aaa;
filepath= name + "/mails.txt";
mkdir(name.c_str(),0666);
//toch("mails.txt",0600);
log.open(name.c_str(), ios::in|ios::out|ios::ate);
if(!log.is_open()){
log.close();
log.open(name.c_str(), ios::in|ios::out|ios::trunc);
}
if(!log.is_open())cout<<"error"<<endl;
log<<flush;
cout<<"message written"<<endl;
}
如果有像 mkdir 这样的系统命令用于创建 .txt,我认为它也会有所帮助
Hi I'm trying to use a fstream file handle doing following:
- write to file
- read from file
- create file(if not existing)
the problem:
For some reason I am not able to make it creating the file.
filepath= name + "/mails.txt";
mkdir(name.c_str(),0600);
log.open(filepath.c_str(), ios::in|ios::out|ios::ate);
if(!log.is_open())cout<<"error"<<endl;
log<<flush;
if the file exists its doing his job but when the file does not exist it wont.
edit: because i badly failed to poste the code in a comment i try it here :D
user::user(string aaa)
{
string filepath;
name=aaa;
filepath= name + "/mails.txt";
mkdir(name.c_str(),0666);
//toch("mails.txt",0600);
log.open(name.c_str(), ios::in|ios::out|ios::ate);
if(!log.is_open()){
log.close();
log.open(name.c_str(), ios::in|ios::out|ios::trunc);
}
if(!log.is_open())cout<<"error"<<endl;
log<<flush;
cout<<"message written"<<endl;
}
if there is a system commant like mkdir for creating the .txt it would help too i think
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 ios::in 时,Fstream 无法创建文件。它只能打开现有文件。
您应该做的是,首先检查它是否打开文件。如果没有,请关闭它,清除其状态,然后使用 ios::out 打开 - 这将创建该文件。
编辑:
如果指定 ios::trunc ,则可以使用 ios::in 来创建文件。但是,如果该文件存在,那么您将删除其所有内容。
Fstream cannot create a file when using the
ios::in
. It can only open existing files.What you should do, is first, check if it opens a file. If it does not, close it, clear its state, and open with
ios::out
- this will create the file.EDIT:
You can create a file using
ios::in
if you specifyios::trunc
. However, if the file exists, then you will be deleting all its contents.