opendir
DIR *opendir(const char *name);
功能:
打开目录
参数:
name:目录文件路径
返回值:
成功返回目录流指针
失败返回NULL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #include "../head.h" int ListDir(char *pdirname) { DIR *dp = NULL; struct dirent *pp = NULL; dp = opendir(pdirname); if(NULL == dp) { return -1; } while (1) { pp = readdir(dp); if (NULL == pp) { break; } if ('.' == *pp->d_name) { continue; } printf("pp->d_name = %s/%s\n", pdirname, pp->d_name); } closedir(dp); return 0; } int main(void) { char dirname[256] = {0}; printf("请输入目录路径:\n"); scanf("%s", dirname); ListDir(dirname); return 0; } |
closedir
int closedir(DIR *dirp);
功能:
关闭目录流指针
参数:
dirp:目录流指针
返回值:
成功返回0
失败返回-1
readdir
struct dirent *readdir(DIR *dirp);
功能:
读取目录项
参数:
dirp:目录流指针
返回值:
成功返回目录项指针
失败返回NULL
读到末尾返回NULL
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
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]; /* Null-terminated filename */
};
路径: ../file.txt
文件名:file.txt
链接文件:
1.软链接(符号链接)
ln -s 要链接向的文件名 软链接文件名
ln -s b.txt a.txt
a.txt -> b.txt
通过文件名进行链接
普通文件:
文件名 -> inode -> 数据块
软链接:
软连接文件名 -> inode -> 数据块 -> 链接向的文件名 -> inode -> 数据块
int symlink(const char *target, const char *linkpath);
功能:
创建一个linkpath的软连接文件,里面存放target字符串
参数:
target:链接向的文件名
linkpath:软链接文件名
返回值:
成功返回0
失败返回-1
ssize_t readlink(const char *restrict path, char *restrict buf, size_t bufsize);
功能:
读取软链接文件本身内容
参数:
path:软链接文件名
buf:存放软链接文件内容的缓冲区
bufsize:缓冲区的大小
返回值:
成功返回读取的字节数
失败返回-1
2.硬链接
ln 要链接的文件名 硬链接文件名
通过在磁盘中存放的inode节点进行链接
删除文件链接关系断开
link
int link(const char *oldpath, const char *newpath);
功能:
创建一个newpath的硬链接文件
参数:
oldpath:要链接的文件名
newpath:硬链接文件名
返回值:
成功返回0
失败返回-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include "../head.h" int main(void) { FILE *fp = NULL; char tmpbuff[4096] = {0}; symlink("file.txt", "a.txt"); fp = fopen("a.txt", "r"); if (NULL == fp) { perror("fail to fopen"); return -1; } fgets(tmpbuff, sizeof(tmpbuff), fp); printf("%s\n", tmpbuff); fclose(fp); memset(tmpbuff, 0, sizeof(tmpbuff)); readlink("a.txt", tmpbuff, sizeof(tmpbuff)); printf("连接文件本身的数据:%s\n", tmpbuff); return 0; } |
unlink
int unlink(const char *pathname);
功能:
删除链接文件名,并让硬链接个数-1 ,如果一个磁盘空间硬链接个数为0,需要回收磁盘空间
参数:
pathname:链接文件名
返回值:
成功返回0
失败返回-1
1 2 3 4 5 6 7 8 9 | #include "../head.h" int main(void) { link("file.txt", "a.txt"); unlink("file.txt"); return 0; } |