如何通过相对路径获得绝对路径和读目录

时间:2022-11-27 14:30:27
 #include <limits.h>
#include <stdlib.h>
char *realpath(const char *path,char*resolved_path); //相对路径为path,绝对路径将放在resolved_path所指空间
//两个参数都是char*类型

return value:
If there is no error, realpath() returns a pointer to the
resolved_path.Otherwise, it returns a NULL pointer, the contents of the array resolved_path are undefined, and errno is set to indicate the error.
返回值:如果相对路径和参数给的没有错将返回的是相对路径所在的绝对路径,否则返回的是一个NULL。
下面我们来看看这函数的用法:
如何通过相对路径获得绝对路径和读目录
这里的c_str函数为了与c语言兼容,在c语言中没有string类型,是c++ 中 string类 (class) 的 函数,它能把 string类 的对象里的字符串 转换成 C 中 char 型变量 的 字符串。
运行结果:
如何通过相对路径获得绝对路径和读目录

读取路径下有那些文件

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

struct dirent {

ino_t d_ino;/* inode number */
off_t d_off;/* not an offset; see NOTES */
unsigned short d_reclen;/* length of this record */
unsigned char d_type;/* type of file; not supported by all filesystem types */
char d_name[256]; /* filename */
};

至于这里的DIR类型我们来找找看:

#include <sys/types.h>
#include <dirent.h>

DIR *opendir(const char *name);
DIR *fdopendir(int fd);

可以看到这两个函数的返回值是DIR类型,所以我们这里也就用一下这两个函数,这两个函数的都是用来打开目录的,我们看看man手册里说的:The opendir() and fdopendir() functions return a pointer to the direc‐tory stream. On error, NULL is returned, and errno is set appropri‐ately.
目录文件类型:

 DT_BLK      This is a block device.
DT_CHR This is a character device.
DT_DIR This is a directory.
DT_FIFO This is a named pipe (FIFO).
DT_LNK This is a symbolic link.
DT_REG This is a regular file.
DT_SOCK This is a UNIX domain socket.
DT_UNKNOWN The file type is unknown.

通过相对路径读取绝对路径:

  1 #include <sys/types.h> 
2 #include <dirent.h>
3 #include <dirent.h>
4 #include <unistd.h>
5
6 #include <iostream>
7 using namespace std;
8
9 int main()
10 {

11 DIR *dir = opendir("./");
12 dirent* pent = NULL;
13 while(NULL != (pent = readdir(dir)))
14 {
15 switch(pent->d_type)
16 {
17 case DT_BLK:
18 cout<<"this is block file:>"<<pent->d_name<<endl;
19 break;
20
21 case DT_CHR:
22 cout<<"this is char file:>"<<pent->d_name<<endl;
23 break;
24 case DT_DIR:
25 cout<<"this is direction file:>"<<pent->d_name<<endl;
26 break;
27 case DT_FIFO:
28 cout<<"this is fifo file:>"<<pent->d_name<<endl;
29 break;
30 case DT_LNK:
31 cout<<"this is link file:>"<<pent->d_name<<endl;
32 break;
33 case DT_REG:
34 cout<<"this is regular file:>"<<pent->d_name<<endl;
35 break;
36 case DT_SOCK:
37 cout<<"this is socke tfile:>"<<pent->d_name<<endl;
38 break;
39 case DT_UNKNOWN:
40 cout<<"this is noconfigur file:>"<<pent->d_name<<endl;
41 break;
42 }
43 }
44 return 1;
45 }

struct dirent *readdir(DIR *dirp);
DIR *opendir(const char *name);

如何通过相对路径获得绝对路径和读目录
对当前目录进行读取:

        当期目录:

如何通过相对路径获得绝对路径和读目录

如何通过相对路径获得绝对路径和读目录

目录的其他操作函数,用到的时候可以使用man手册查看,在函数的括号里已经表明了手册序号:
getdents(2), read(2), closedir(3), dirfd(3), ftw(3), offsetof(3), opendir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3)