ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
here name is a char variable, i just can't think of how to test if the variable has a value (tried if(name == NULL))... If I do a printf("%s\n", name) I get P??? ?...
When you declare a variable in C (this is C right?) it isn't initialized to anything in particular, it gets whatever happens to be in the memory space it was given. So rather then testing if it is uninitialized how bout making sure you initialize it to something on declaration? If it is a char * then set it equal to NULL (if you plan on dynamically allocating memory) or to an empty string of the correct size (if you are statically allocating memory).
Tried that but didn't work... This is what I've got so far:
Code:
int main(int argc, char *argv[]) {
char name[64] = NULL, salt[32], password[64], newpwd[64];
int menu_option;
struct passwd *pwd; /* Pointer to a structure in the pwd.h header file */
struct spwd *shadow; /* Pointer to a structure in the shadow.h header file */
int optch; /* Current option charachter */
char stropts[] = ":u:h"; /* Supported agruments */
while((optch = getopt(argc, argv, stropts)) >= 0) {
switch (optch) {
case 'h':
usage(argv[0]);
return 0;
case 'u':
sprintf(name, "%s", optarg);
break;
case ':':
fprintf(stderr, "No argument specified for -%c option\n", optopt);
return 1;
case '?':
printf("Unknown option -%c.\n", optopt);
printf("For help on usage please use: %s -h\n", argv[0]);
return 1;
}
}
if(name == NULL) {
strcpy(name, getenv("USER"));
printf("Using current username: %s\n", name);
}
But when I run without parameters it doesn't ask me for a name, just uses nothing as a name and continues... and if i use the -u switch it uses the default system environment name...
AMMullan, jtshaw's answer + you could use smth like this:
#define DEFUALT_LEN 1024
char* name=NULL;
int getUserName()
{
if(name==NULL)
name=(char*)calloc(DEFAULT_LEN,sizeof(char)); // alloc memory for name if not yet and set it to 0
if(name[0]==0) strncpy(name,getenv("USER"),DEFAULT_LEN); //check if name string has zero length and set it to env{USER} in this case
}
BestRegards,
Oleg.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.