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

谁说胖子不能爱 提交于 2020-01-02 07:56:46

问题


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?


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/6477568/how-to-create-a-text-file-in-a-folder-on-the-desktop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!