The method in linux to obtain the absolute path to a file by means of a file descriptor

  • 2020-05-15 03:28:08
  • OfStack

In linux, sometimes we only know the file descriptor but not its name and its full path. What if we want to get its path? In fact, it is quite simple that every file opened in linux is recorded in the /proc/self/fd/ directory, where the file (/proc/self/fd/ file descriptor) is the file corresponding to the file descriptor. So let's stop here and say 1 function:

readlink (get the file the symbolic link refers to)

Correlation functions stat, lstat, symlink

The header file #include < unistd.h >

Define the function int readlink (const char *path, char *buf, size_t bufsiz);

The readlink() function stores the symbolic concatenation contents of the parameter path into the memory space referred to by the parameter buf. The returned contents do not end with NULL as a string, but the number of characters in the string is returned. If the parameter bufsiz is less than the content length of the symbolic connection, the excessively long content will be truncated.

The return value is passed to the specified file path string on success, and returned to -1 on failure. The error code is stored in errno.

Error code EACCESS was denied access to the file

The EINVAL parameter bufsiz is negative
EIO I/O access error.
The file ELOOP is trying to open has too many symbolic links.
The path name for the ENAMETOOLONG parameter path is too long
The file specified by the ENOENT parameter path does not exist
The ENOMEM is out of core memory
The directory in the ENOTDIR parameter path path exists but is not a real directory.


Based on the above, the following simple functions are obtained to obtain the file path:


std::string get_file_name (const int fd)
{
  if (0 >= fd) {
    return std::string ();
  }

  char buf[1024] = {'\0'};
  char file_path[PATH_MAX] = {'0'}; // PATH_MAX in limits.h
  snprintf(buf, sizeof (buf), "/proc/self/fd/%d", fd);
  if (readlink(buf, file_path, sizeof(file_path) - 1) != -1) {
    return std::string (file_path);
  }

  return std::string ();
}




Related articles: