question about filestream

I saw some tutorial pages on the internet about how to read files using C++
But I'm kind of confused because there isn't anything in code indicate where the file is from. So I think I need some explanation.
Thanks!!
You have to specify the filename when the file is opened by passing it the constructor or to the open member function.
http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream
http://en.cppreference.com/w/cpp/io/basic_ifstream/open
If with "where is the file from" you mean the location of the file:

1
2
3
ofstream ofs("hereisyourfilename");
ofs << "this is the text\n";
ofs << 123 << endl;


The initializer takes a const char* string.
Last edited on
So is it that as long as you get the filename right it will get the file for you no matter where the file is?
what if there are two files have the same name but in different folders?
It will open file in current (working) folder. If you want to open file which is in another folder you may write full path:
ofstream ofs("C:\\some_folder\\some_file");
There is version of the constructor (and open() function) which takes std::string, if you use them.
What you pass is actually the file path, so you can give a full path, or a relative path. If you just specify the filename that is a relative path. Relative paths are relative to the working directory of program. If you start your program by double clicking on the executable file the working directory will be the directory where the executable file is located. If you start your program from the command line the working directory will be the directory that you set using the cd command. If you start your program from an IDE the working directory is often set to the project directory (not the source directory) but this can differ between IDEs.
Ok, now I see

Thanks very much!!
Topic archived. No new replies allowed.