Linux C gets the file name through a filename descriptor

Source: Internet
Author: User

Each file that is opened in Linux is recorded in the/proc/self/fd/directory, where the file (/proc/self/fd/file description symbol; This file is a symbol file) is the file that corresponds to the file descriptor.
and Readlink can get the file that the symbolic connection refers to
Function Prototypes:

ssize_t readlink(constcharchar *buf, size_t bufsiz);

Function Description:

readlink()会将参数path的符号连接内容存到参数buf所指的内存空间,返回的内容不是以NULL作字符串结尾,但会将字符串的字符数返回。若参数bufsiz小于符号连接的内容长度,过长的内容会被截断。返回值 执行成功则传符号连接所指的文件路径字符串,失败则返回-1I/O 存取错误。ELOOP 欲打开的文件有过多符号连接问题。ENAMETOOLONG 参数path的路径名称太长ENOENT 参数path所指定的文件不存在ENOMEM 核心内存不足ENOTDIR 参数path路径中的目录存在但却非真正的目录。

Get the filename by file descriptor source code:

#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>#include <string.h>Const Char*file_name ="A.txt";intMain () {intFdif(FD = open (file_name, o_rdonly)) = =-1){fprintf(stderr,'%s Open:%s\n ', Flow_rx_file, Strerror (errno));return-1; }Charbuf[1024x768] = {' + '};Charfile_path[1024x768] = {' + '};snprintf(BUF,sizeof(BUF),"/proc/self/fd/%d", FD); Readlink (Buf,file_path,sizeof(File_path)-1);printf("%s\n", File_path);return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux C gets the file name through a filename descriptor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.