-2

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

asdf
  • 1,475
  • 1
  • 9
  • 11

1 Answers1

2

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.

Jan S
  • 1,831
  • 15
  • 21
  • What exactly did you try? Can you paste your code? – Jan S Oct 14 '11 at 09:11
  • 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"< – asdf Oct 14 '11 at 13:16
  • instead of `log.open(name.c_str()` try using `log.open(filepath.c_str()` Otherwise the code is fine - it creates a new file for me. – Jan S Oct 15 '11 at 09:27