Tuesday, 15 January 2013

c - How to check if soft link exists or not -



c - How to check if soft link exists or not -

user: ls -lt lrwxrwxrwx 1 user sw-team 9 jun 18 19:01 new_link -> test/file

i have soft link mentioned above. want check whether new_link(not linked file) exists or not. tried below checking if final destination file (test/file) exists or not.

access(filename,f_ok) stat() open() fopen()

i want find in c language not in shell script.please tell me how find if new_link exists before checking linked file?

use lstat - symbolic link status:

the lstat() function shall equivalent stat(), except when path refers symbolic link. in case lstat() shall homecoming information link, while stat() shall homecoming info file link references.

(emphasis mine.)

lstat homecoming non-zero, , errno set enoent if link (or other part of path) not exist.

example:

#include <stdio.h> #include <stdbool.h> #include <sys/stat.h> bool symlink_exists(const char* path) { struct stat buf; int result; result = lstat(path, &buf); homecoming (result == 0); } void test(const char* path) { bool exists = symlink_exists(path); printf("%s does%s exist.\n", path, exists ? "" : " not"); } int main(int argc, char** argv) { test("/bin/sh"); test("/etc/no_such_thing"); homecoming 0; }

output:

class="lang-none prettyprint-override">/bin/sh exist. /etc/no_such_thing not exist.

c linux symlink

No comments:

Post a Comment