How to implement readlink to find the path

后端 未结 5 1915
悲&欢浪女
悲&欢浪女 2020-12-09 03:33

Using the readlink function used as a solution to How do I find the location of the executable in C?, how would I get the path into a char array? Also, what do the variables

5条回答
  •  醉梦人生
    2020-12-09 04:01

    Let's look at what the manpage says:

     readlink() places the contents of the symbolic link path in the buffer
     buf, which has size bufsiz.  readlink does not append a NUL character to
     buf.
    

    OK. Should be simple enough. Given your buffer of 1024 chars:

     char buf[1024];
    
     /* The manpage says it won't null terminate.  Let's zero the buffer. */
     memset(buf, 0, sizeof(buf));
    
     /* Note we use sizeof(buf)-1 since we may need an extra char for NUL. */
     if (readlink("/proc/self/exe", buf, sizeof(buf)-1) < 0)
     {
        /* There was an error...  Perhaps the path does not exist
         * or the buffer is not big enough.  errno has the details. */
        perror("readlink");
        return -1;
     }
    

提交回复
热议问题