user7085794 user7085794 - 1 year ago 147
C Question

Using strcat for permissions in C

Please help, going insane, been trying to do this for 8 hours now and it never works. I realise I can print out the permissions of a file easily, I've managed to do that, but I can't use this method to return it.

char *printMode(mode_t mode)
{

char *mode_s = (char *) calloc(MODE_S_LEN, sizeof(char));
int a = (S_ISDIR(mode));

mode_s = ((S_ISDIR(mode)) ? "d" : "-");
strcat(mode_s, ((mode & S_IRUSR) ? "r" : "-"));
strcat(mode_s, ((mode & S_IWUSR) ? "w" : "-"));
strcat(mode_s, ((mode & S_IXUSR) ? "x" : "-"));
strcat(mode_s, ((mode & S_IRGRP) ? "r" : "-"));
strcat(mode_s, ((mode & S_IWGRP) ? "w" : "-"));
strcat(mode_s, ((mode & S_IXGRP) ? "x" : "-"));
strcat(mode_s, ((mode & S_IROTH) ? "r" : "-"));
strcat(mode_s, ((mode & S_IWOTH) ? "w" : "-"));
strcat(mode_s, ((mode & S_IXOTH) ? "x" : "-"));

return mode_s;
}

Answer Source

The problem is these two lines:

char *mode_s = (char *) calloc(MODE_S_LEN, sizeof(char));
mode_s = ((S_ISDIR(mode)) ? "d" : "-");

The first one make mode_s point to the memory you allocate. The next line makes it point to either "d" or "-". You reassign the pointer and make it point somewhere else.

Since you initialize the memory you allocate to zero, you could use strcat here too. Or strcpy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download