简体   繁体   中英

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

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?

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

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

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM