tags:

views:

555

answers:

3

Hey all, I have a problem, I don't know how to create a file in C++ in a specific place in the PC. For example a file (.txt) in C:\file.txt. Can anybody help me? Thank you :)

+2  A: 

It's probably fooling you because it's easier than you think. You just open a file for create and give it that path name. Voila.

See, eg,

// fstream::open
#include <fstream>
using namespace std;

int main () {

  fstream filestr;

  // You need a doubled backslash in a C string
  filestr.open ("C:\\file.txt", fstream::out);

  // >> i/o operations here <<

  filestr.close();

  return 0;
}
Charlie Martin
+2  A: 
#include <stdio.h>

....
FILE *file;
file = fopen("c:/file.txt", "w");
David Nehme
Note that this clear the file if it exists.
Sam Hoice
Shouldn't you escape the backslash?
David Rodríguez - dribeas
@David: There will be a warning -- unknown escape character '\f' with this fopen statement.
dirkgently
Also isn't stdio c-style c++?
Skilldrick
+6  A: 
#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ofstream ofs("c:\\file.txt");
  if (ofs) {
     ofs << "hello, world!\n";
  }
  return 0;
}
dirkgently