fstream 只是不会创建文件

发布于 2024-12-10 06:35:42 字数 887 浏览 6 评论 0原文

您好,我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2024-12-17 06:35:42

使用 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 specify ios::trunc. However, if the file exists, then you will be deleting all its contents.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文