views:

422

answers:

5

I Googled around, but didn't find any good example / tutorial.

So i asking you SOF: How do you Read and Write to a File in C++?

+4  A: 

That is interesting. I typed How do you Read and Write to a File in C++ into google and found lots of results, like this one.

Sean Bright
+2  A: 

A couple references to get you started:

lc
+1  A: 

Try using the fopen, fwrite, fread, and fclose functions for the most basic file I/O, e.g.

#include <stdio.h>

int main(int argc, char** argv)
{
  FILE* f = fopen("hello world.txt", "wb");
  if(!f) return -1;
  fwrite("Hello World", sizeof(char), 11, f);
  fclose(f);
  return 0;
}

There are other functions that can help such as fprintf, fscanf, fputs and fgets.

jheriko
A: 

If you don't like to do basic file-handling by yourself you might want to look at The boost library.

Leonidas
A: 

You might look at things like fprintf() and fscanf(). But to get you started:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

#define SHOW(X) cout << # X " = " << (X) << endl

void write()
{
  ofstream o("filefoo");
  o << "test 1 2 3" << endl;
}

void read()
{
  ifstream i("filefoo");
  string s[4];
  i >> s[0] >> s[1] >> s[2] >> s[3];

  for( int j=0; j<4; j++ )
    SHOW(s[j]);
}

int main()
{
  write();
  read();
}
Mr.Ree