How to create a text file in a folder on the deskt

2019-05-13 16:13发布

I have a problem in my project. There is a project folder on my desktop. I want to create a text file and write something include this text file. That is my code:

ofstream example("/Users/sample/Desktop/save.txt");

But I want to it could been run the other mac. I don't know what I should write addres for save.txt.

Can anyone help me?

3条回答
2楼-- · 2019-05-13 16:42

Rules defining where-you-should-save-file vary from platform to platform. One option would be to have it part of your compile script (that is you #define SAVEGAME_PATH as part of your compilation configuration), and thus your code itself remain more platform-agnostic.

The alternative is to find a save-data-management library that is already designed to be ported across different platforms. Whether it'd be a C or C++ or whatever-binary-interoperable library then no longer matters.

Just don't expect that to be part of C++ (the language).

查看更多
Anthone
3楼-- · 2019-05-13 16:53

if you want your program to run across platform,you'd better use the relative path. eg. "./output.txt",or better “GetSystemDirectory()”to obtain the system directory to create a file,and then you could write or read the file with the same path..

查看更多
三岁会撩人
4楼-- · 2019-05-13 16:55

Create a file and write some text to it is simple, here is a sample code:

   #include <iostream>
   #include <fstream>
   #include <string>
   using namespace std;

   int main() 
   {
      std::ofstream o("/Users/sample/Desktop/save.txt");

      o << "Hello, World\n" << std::endl;

      return 0;
   }

I hope that answers your question but I am not sure if i understand your question correctly, If not please add the details correctly of what you are trying to acheive.

[Update]: Okay I guess the comment clears the problem.
Your real question is, You want to save the file in the desktop of the user who is playing the game. So getting the path of the current user's desktop is the problem.

I am not sure if there is an portable way to get desktop path but it can be done in following ways:

In Windows:
Using the SHGetSpecialFolderPath() function.

Sample code:

char saveLocation[MAX_PATH] = {0};

SHGetSpecialFolderPath(NULL, saveLocation, CSIDL_DESKTOPDIRECTORY, FALSE);

//Now saveLocation contains the path to the desktop
//Append your file name to it
strcat(saveLocation,"\\save.txt");

ofstream o(saveLocation);

In Linux:
By using environment variables $HOME

sample code:

string path(getenv("HOME"));
path += "/Desktop/save.txt";
ofstream o(path);
查看更多
登录 后发表回答