简体   繁体   English

如何使用C语言查找桌面路径?

[英]How to find desktop path using C language?

Can anybody please tell me how I can get the desktop path(environment variable) using C language commands. 任何人都可以告诉我如何使用C语言命令获取桌面路径(环境变量)。

Scenario is that I want to save a file on desktop.What I can do is just to give a fixed desktop path and a filename to save the file. 场景是我想在桌面上保存文件。我能做的只是提供固定的桌面路径和文件名来保存文件。 But after giving this fixed path ,my code will become rigid and will not work on anyother computer having different desktop path (environment variable). 但是在给出这个固定路径之后,我的代码将变得僵硬,并且不能在具有不同桌面路径(环境变量)的任何其他计算机上工作。 My question is can I make my code generalize which can work on any windows based machine by capturing the environment variable of desktop , using C language? 我的问题是,我是否可以通过使用C语言捕获桌面的环境变量来使我的代码可以在任何基于Windows的机器上工作?

Regards 问候

You can use the function getenv() to access environment variables: 您可以使用函数getenv()来访问环境变量:

The value of an environment variable can be accessed with the getenv function. 可以使用getenv函数访问环境变量的值。 This is declared in the header file stdlib.h. 这是在头文件stdlib.h中声明的。

For Windows systems, USERPROFILE should be good if you append \\Desktop to it (see the link provided by mgiuca, for example). 对于Windows系统,如果您将\\Desktop附加到它,则USERPROFILE应该是好的(例如,请参阅mgiuca提供的链接 )。 Note that the path will contain spaces in most cases, so handle it accordingly. 请注意,在大多数情况下,路径将包含空格,因此请相应地处理它。

Also, using environment variables to get the path of the desktop folder isn't the best way and might not work in some cases (also see other SO answers to this topic, like this one ), so see this answer as an answer to your specific question, especially for the "environment variables in C++" part. 此外,使用环境变量拿到桌面文件夹的路径是不是最好的方式,并在某些情况下可能无法正常工作(另见其他SO回答这个题目,像这一个 ),所以看到这个答案的回答为您具体问题,特别是对于“C ++中的环境变量”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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