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(), 开发者_JS百科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
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.
精彩评论