0

I got the user id to add it to the file path. But am having trouble creating the file. How do I add the user id to the file path? I used strcpy but that does not seem to work. Here is my code.

  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  register struct passwd *pw;
  register uid_t uid;
  uid = geteuid ();
  pw = getpwuid (uid);
  char str[1000];
  strcpy(str, "/home/" );
  strcpy(str, pw->pw_name );
  strcpy(str, "/Documents/test.txt" );
  int openFile = creat(str, mode);
Aaron
  • 4,380
  • 19
  • 85
  • 141
  • 1
    Three times strcpy() ??? maybe you wanted strcpy(...); strcat(...); strcat(...) ? Or even better" `ret = snprintf(str, sizeof str, "%s/%s/%s" "/home" , pw->pw_name, "Documents/test.txt"); if (ret >= sizeof str) {... error...}` – wildplasser Mar 30 '15 at 23:14
  • 1
    Thanks, add it as an answer to I cam mark you as correct – Aaron Mar 30 '15 at 23:15

2 Answers2

4

Three times strcpy() ? maybe you wanted:

strcpy(str, "/home/");
strcat(str, pw->pw_name);
strcat(str, "/Documents/test.txt");

? Or even better:

int ret;
ret = snprintf(str, sizeof str, "%s/%s/%s"
   , "/home" , pw->pw_name, "Documents/test.txt");
if (ret >= sizeof str) {... error...}
wildplasser
  • 43,142
  • 8
  • 66
  • 109
1

This is a fine purpose for snprintf (in stdio.h). One line:

snprintf(str, 1000, "/home/%s/Documents/test.txt", pw->pw_name);

Even better to first verify that pw->pw_name is not null prior.

The reason that your multiple strcpy does not work is that you write to the same location in memory at each call.

I would not advise that you do this, but you could use strcpy provided you updated the pointer after each call. One example:

char *loc = str;
strcpy(loc, "/home/" );
loc += strlen("/home/");
strcpy(loc, pw->pw_name );
loc += strlen(pw->pw_name);
strcpy(loc, "/Documents/test.txt" );

This, however, would be an issue had you chosen a small buffer (shorter than the combined number of characters of all three strings + one more for the terminating null) — a buffer overflow.

snprintf gives the benefit of ensuring that you don't exceed that bound:

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')).

Demi
  • 6,147
  • 7
  • 36
  • 38