Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create file on desktop in c++

Tags:

c++

I know that to create a file in c++ we use following code

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream out;
    out.open("exemple.txt");
    return 0;
}

My question is the following, I want to create example.txt file on desktop or in an other directory. To simplify it let's take the desktop for now.

Please help me how to do it?

Like this?

out.open("example.txt","C:\Users\David\Desktop");
like image 747
dato datuashvili Avatar asked Jul 29 '10 05:07

dato datuashvili


1 Answers

The main problem with your code is that the '\' is the escape character in C/C++.

So when you put the string: "C:\Users\David\Desktop" The slashes are escaping the next character and thus they are not actually part of the string and what the executable gets is "C:UsersDavidDesktop" to compensate for this there are two alternatives:

  • Use the escape sequence for the slash '\\' thus giving you: "C:\\Users\\David\\Desktop"
  • Or use the '/' character to separate directories in the path.
    • Personally I prefer this option as it is portable between all modern OS's now. (Win/Linux/MAC)

Your secondary problem is that you are using the open incorrectly. Just specify the path name as 1 long string (this is called an absolute path). Personally I prefer to provide the file name to the constructor rather than explicitly calling open (but that's just a personal preference thing).

#include <fstream>
int main()
{
    std::ofstream out1("C:\\Users\\David\\Desktop\\exemple1.txt");

    std::ofstream out2("C:/Users/David/Desktop/exemple2.txt");
}

A minor note. Hard coding the path to the desktop directory is not good practice. You are tightly coupling your application to how that version of the OS lays out the file system. Each OS usually provides a technique on how to find users directories please see your OS documentation for more details (or ask another question on StackOverflow).

Also note boost provides a file system class to abstract the file system across all major OS's. Its useful to get to know how it works rather than representing files as strings; the string representation can get slightly error prone when you build complex paths (eg paths with spaces). characters embedded into them.

like image 176
Martin York Avatar answered Sep 21 '22 21:09

Martin York