views:

273

answers:

5

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)

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));                 
}
+1  A: 

This is going to be platform specific, as there is no intrinsic way in the C programming language to do this.

It looks like you're on a Unix-based system, so you'll probably want to get the environment variable USER which is usually the logon name.

bobbymcr
+1  A: 

On unix-like systems use the function getlogin from unistd.h.

sepp2k
+2  A: 

This is not a C question but is more like a UNIX question. There is no portable way of getting the username and current working directory in C language.

However, by viewing your example, I can tell you are trying to print the current UNIX user name and current working directory.

If you need current working directory in UNIX check getcwd function.

If you need current user name you can either call a separate whoami process within your C program, or check the getuid function call.

Pablo Santa Cruz
+4  A: 

Aside from the fact that you should be using the environment variable USER instead of LOGNAME, you shouldn't be using environment variables for this in the first place. You can get the current user ID with getuid(2) and the current effective user ID with geteuid(2), and then use getpwuid(3) to get the user name from the user ID from the passwd file:

struct passwd *p = getpwuid(getuid());  // Check for NULL!
printf("User name: %s\n", p->pw_name);

To get the current computer name, use gethostname(2):

char hostname[HOST_NAME_MAX+1];
gethostname(hostname, sizeof(hostname));  // Check the return value!
printf("Host name: %s\n", hostname);
Adam Rosenfield
+1  A: 

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

Also does the job.

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.

Neeraj