0

I have the following problem. I would like to open and save a string to file.

ofstream file("file");
file << "example" << endl;
file.close()

Rather simple stuff. The problem is... the code above doesn't seem to create any files in my project directory. I have tried to use "locate" in terminal to find my file - withoud any results. What is interesting - I can open the file using ifstream and read from it, without any particular problems.

What the heck is going on here? Where should I look for the file created? P.S. On Windows everything works 100% fine.

DorianOlympia
  • 841
  • 1
  • 10
  • 22

1 Answers1

2

in my project directory

Where did you read that this is where to look? We should collaborate and correct that resource.

I have tried to use locate in terminal

It probably hasn't been indexed yet.

You need to look in the current working directory of the terminal that started the program.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • This is precisely why I think file paths should be absolute. – erip Feb 26 '16 at 18:13
  • Okey, you are right. Now I see the problem occurs only when I run the code from the Clion console. Apparently it saves those files "somewhere"... but where this mysterious place might be? – DorianOlympia Feb 26 '16 at 18:18
  • @erip, no, why? I'd rather say, they **never** should be absolute. Current working directory is a very good place. – SergeyA Feb 26 '16 at 18:19
  • @erip: Huh? No, quite the contrary. The "current working directory" feature is there for your benefit. Why would you ever hard-code an absolute path? That gives your program the minimum possible shelf-life. – Lightness Races in Orbit Feb 26 '16 at 18:23
  • Maybe it's me. I've had nothing but trouble when working with relative paths... Absolute paths are _absolute_, so everything else that relies on that resource knows exactly where to look. For instance, [when bundling](http://stackoverflow.com/questions/26902827/fopen-with-a-app-file) – erip Feb 26 '16 at 18:24
  • @PreferenceBean they are not. And ls -a doesn't show them as well. – DorianOlympia Feb 26 '16 at 18:27
  • @DorianOlympia: Then the files weren't written at all. Check that your program has permissions to write into the current working directory, and to create files there. Add some basic error checking to your IOStreams usage. – Lightness Races in Orbit Feb 26 '16 at 18:37
  • @erip: That's a hack. A workaround. Using a giant hammer to fit the pieces of the space station into place. It'll come back to bite you very, very quickly. You'd be better off taking the ten minutes you need to fix the actual problem. – Lightness Races in Orbit Feb 26 '16 at 18:38
  • @PreferenceBean How couldn't they be written, if I'm able to read them using ifstream? And I'm able to do it in another instance of my program? – DorianOlympia Feb 26 '16 at 18:46
  • @DorianOlympia: That is not possible. You are misinterpreting your results. – Lightness Races in Orbit Feb 26 '16 at 18:48