Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming. Printing current user

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));                 
}
like image 901
user69514 Avatar asked Sep 20 '09 19:09

user69514


People also ask

How to prompt user input in C?

In C, we can get user input like this: // strings char name[10]; printf("Enter your name: "); fgets(name, 10, stdin); printf("Hello %s!

How do I find my C username in Linux?

Use char *cuserid(char *s) found in stdio.

How can I print in C?

You can print all of the normal C types with printf by using different placeholders: int (integer values) uses %d. float (floating point values) uses %f. char (single character values) uses %c.


1 Answers

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);
like image 50
Adam Rosenfield Avatar answered Oct 05 '22 23:10

Adam Rosenfield