You are not logged in.

#1 2009-05-21 18:14:47

FSM
Member
Registered: 2008-04-14
Posts: 33

[SOLVED][Newbie C++ Question] Writing with fstream

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

#2 2009-05-21 18:33:00

livibetter
Member
From: Taipei
Registered: 2008-05-14
Posts: 95
Website

Re: [SOLVED][Newbie C++ Question] Writing with fstream

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

#3 2009-05-21 18:37:30

FSM
Member
Registered: 2008-04-14
Posts: 33

Re: [SOLVED][Newbie C++ Question] Writing with fstream

That works. Thank you!

FSM

Offline

#4 2009-05-21 19:12:42

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: [SOLVED][Newbie C++ Question] Writing with fstream

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

#5 2009-05-21 19:43:01

FSM
Member
Registered: 2008-04-14
Posts: 33

Re: [SOLVED][Newbie C++ Question] Writing with fstream

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

#6 2009-05-21 20:00:16

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: [SOLVED][Newbie C++ Question] Writing with fstream

tomd123 wrote:

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. tongue

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

Board footer

Powered by FluxBB