C编程。打印当前用户 [英] C Programming. Printing current user
问题描述
在C编程中,如何获取当前用户和当前工作目录。
我试图打印这样的东西:
In C programming how do you get the current user and the current working directory. I'm trying to print something like this:
asmith@mycomputer:~/Desktop/testProgram:$
(user) (computerName) (current directory)
我有以下代码,用户名显示为NULL。任何想法我在做错什么?
I have the following code, but the username is showing as NULL. Any ideas what I'm doing wrong?
void prompt()
{
printf("%s@shell:~%s$", getenv("LOGNAME"), getcwd(currentDirectory, 1024));
}
推荐答案
请注意,一个unix系统。
可能是LOGNAME未设置为您的环境变量
您可以使用 printenv
命令查看环境变量
Note that this will work on a unix system only.
may be LOGNAME was not set as your environment variable
you can see the environment variables using the printenv
command
printf("%s@shell:%s$", getenv("USER"),getenv("PWD"))
此工作也是这样。
但是如上所述你应该不要依赖环境变量,而是使用标准的c函数。如果你真的想使用它们,首先要确定它是否设置。
but as mentioned you shouldn't rely on environment variables, rather use the standard c functions.If you really want to use them, first make sure it is set.
这篇关于C编程。打印当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!