3

I have this code to create a file, when I run it with CLion it prints out to the console but does not create file, how can I fix this? thanks

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ofstream log_file;
    log_file.open("sample23.txt");

    if (log_file.is_open())
        std::cout << "Open";

    log_file << "stuff" << endl;

    log_file.close();

    return 0;
}
ePezhman
  • 4,010
  • 7
  • 44
  • 80
  • 1
    Maybe it creates the file into another directory? http://stackoverflow.com/questions/25834878/how-do-i-change-the-working-directory-for-my-program – nnn Nov 22 '15 at 00:25
  • 1
    You haven't provided necessary information. How do you test if the file is created? Are you looking in the correct directory? Does the directory your program is trying to create the file in (the current working directory) exist? If it does exist, does your program [or the process executing it] have access to create a file? – Peter Nov 22 '15 at 00:43
  • @nnn yeah that was it, write and answer and I'll accept your answer – ePezhman Nov 22 '15 at 00:49

3 Answers3

5

The file may be created into another directory (the working directory).

You can find that location (and change it if needed) as indicated here: How do I change the working directory for my program

Community
  • 1
  • 1
nnn
  • 3,980
  • 1
  • 13
  • 17
1

make sure to flush before closing because file is empty

try this out

ofstream f;
f.open( "sample.txt", ios::out );
f << flush;
f.close();
1

3 things here: 1.) In order to output to another file, you must make another variable like this:

ifstream someoutputfile;
someoutputfile.open("filename");

2.) you actually must make another variable to be "placeholder" of sorts that will automatically assign the first thing your file finds and assigns that to. This may depend on what datatype (int, double, string etc) your input file consists of. Instead of:

log_file << "stuff" << endl;

you can do something like this...

// if my input file is integers for instance..
int data = 0;
log_file >> data; 

This can also work for if your file contains multiple data types. ex:

// if I have two different data types...
string somebody;
int data = 0;
log_file >> data >> somebody;

3.) to output your file data to the screen, just follow a similar way as the example in #1.

someoutputfile << data << somebody << endl;

in addition, dont forget to close the data of BOTH your input and output files: someoutputfile.close() Hope that helps in some way :)