Question

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    struct stat buf;
    int fd;

    if (fd = open(argv[1], O_RDWR | O_CREAT)<0)
    {
        printf("file open error\n");
        return 1;
    }
    if (link(argv[1], "link1") + link(argv[1], "link2")<0)
    {
        printf("error link\n");
        return 1;
    }
    if (fstat(fd, &buf)<0)
    {
        printf("error fstat\n");
        return 1;
    }
    printf("nlinks before = %d \n", buf.st_nlink);
    if (unlink("link2") + unlink("link1") + unlink(argv[1])<0)
    {
        printf("unlink error\n");
        return 1;
    }
    if (fstat(fd, &buf)<0)
    {
        printf("error fstat\n");
        return 1;
    }
    printf("nlinks after = %d \n", buf.st_nlink);
    return 0;
}

Output: nlinks before = 1 nlinks after = 1

Why is st_nlink always = 1 even though the are at least 3 links to the file? Also, if I use lstat instead I get 3 st_nlinks. Why?

Was it helpful?

Solution

if (fd = open(argv[1], O_RDWR | O_CREAT)<0)

should be:

if ( (fd = open(argv[1], O_RDWR | O_CREAT))<0) 

as < has higher precedence than =.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top