Search code examples
linuxstringsystemstatstrcat

linux system stat() method is not working correctly


When I wrote path like this, I stat() was working.

char homePath[] = "../../usr/http/";

if(stat("usr/bin",&file_info) == -1)
{
    strcat(sendMessage, path);
    strcat(sendMessage, "\n\nHTTP/1.1 400 Not Found\n");
    return 0;
}

but the below code is not working. stat() always returns -1. I thought strcat is the problem. But when I check the merged path string, It seems ok. Please let me know how to fix it.

    strcat(path, homePath);
    strcat(path, target);


    if(stat(path,&file_info) == -1)
    {
        strcat(sendMessage, path);
        strcat(sendMessage, "\n\nHTTP/1.1 400 Not Found\n");
        return 0;
    }

Solution

  • The first character's of path might be unprintable. Use strcpy. Safer yet, use strncpy and strncat.

    strncpy(path, homePath, sizeof(path));
    strncat(path, target, sizeof(path) - strnlen(path, sizeof(path)));
    

    Read the Linux man pages to see why the strn versions are preferred.