如何在桌面上的文件夹中创建文本文件 [英] How to create a text file in a folder on the desktop

查看:245
本文介绍了如何在桌面上的文件夹中创建文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中有问题。在我的桌面上有一个项目文件夹。我想创建一个文本文件,并写一些东西包括这个文本文件。这是我的代码:



ofstream示例(/ Users / sample / Desktop / save.txt);



但我想它可以运行其他mac。我不知道我应该为save.txt写什么地址。



任何人都可以帮助我吗?

解决方案

创建文件并写一些文本很简单,这里是一个示例代码:

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

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

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

return 0;
}



我希望能回答你的问题,但我不知道我是否明白你的问题正确,如果没有,请正确添加您想要实现的细节。



[更新]:
好​​,我想评论清除问题。 br>
您的真正问题是, 您想将文件保存在正在玩游戏的用户的桌面上。因此,获取当前用户桌面的路径是个问题。



我不知道是否有可移植的方式获取桌面路径但可以通过以下方式完成:



在Windows中:

使用 SHGetSpecialFolderPath() 功能。 p>

示例代码:



  char saveLocation [ MAX_PATH] = {0}; 

SHGetSpecialFolderPath(NULL,saveLocation,CSIDL_DESKTOPDIRECTORY,FALSE);

//现在saveLocation包含桌面的路径
//将文件名附加到它
strcat(saveLocation,\\save.txt);

ofstream o(saveLocation);

在Linux中:

使用环境变量$ HOME



示例代码:



 字符串路径(getenv(HOME)); 
path + =/Desktop/save.txt;
ofstream o(path);


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

这篇关于如何在桌面上的文件夹中创建文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆