You are not logged in.
Hi,
I am lerning C++ and today I tried to write a little piece of code which saves something to a file. For that, I used the example from http://www.cplusplus.com/reference/iost … m/fstream/:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream filestr ("test.txt", fstream::in | fstream::out);
// >> i/o operations here <<
filestr << "just a test" << endl;
filestr.close();
return 0;
}
It compiles and it runs, but it doesn't create a file! It just works if I create the file beforehand with "touch test.txt". Afaik I have the needed permissions in this folder.
ls -l:
drwxr-xr-x 2 fsm users 4096 May 21 20:17 Cpp_folder
Can anybody help me?
FSM
Last edited by FSM (2009-05-22 14:56:23)
Offline
I think it should be
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream filestr ("test.txt", fstream::out);
if (filestr.fail()) {
cout << "FAIL";
return 1;
}
// >> i/o operations here <<
filestr << "just a test" << endl;
filestr.close();
return 0;
}
only in or out, and use fail() to check if it is opened successful.
Offline
That works. Thank you!
FSM
Offline
not to scrutinize too much, but I always think that adding the arg parameters into main was always good practice. (int argc, char ** argv)
Offline
I know, I just didn't use it because it was not in the example mentioned above (and I tried to keep my programm as near as possible to the example to be sure my problem is not just because of my own code).
But anyway, thank you!
FSM
Offline
not to scrutinize too much, but I always think that adding the arg parameters into main was always good practice. (int argc, char ** argv)
Since the original problem is already resolved, I don't mind dragging this off-topic.
Personally, I disagree with you. If you're never going to use those params, then use the zero-param version of main. It's more clear that way.
Offline