Wednesday, April 20, 2011

How create file in C++ in a specific place in the PC

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 :)

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

0 comments:

Post a Comment