开发者

create file on desktop in c++

开发者 https://www.devze.com 2023-01-09 02:58 出处:网络
I know that to create a file in c++we use following code #include <iostream> #include <fstream>

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 ex开发者_C百科ample.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");


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.


Here's a straight forward way to do it on Linux.

string path(getenv("HOME"));
path += "/Desktop/example.txt";
ofstream outf(path);


Use SHGetSpecialFolderPath function to get desktop folder path in current user http://msdn.microsoft.com/en-us/library/bb762204%28VS.85%29.aspx


    char szPath[MAX_PATH] = {0};
    SHGetSpecialFolderPath(NULL,
                       szpath,
                       CSIDL_DESKTOPDIRECTORY,
                       FALSE);
    strcat(szPath,"\\Test.txt");

    ofstream out;
    out.open(szPath);
0

精彩评论

暂无评论...
验证码 换一张
取 消