Linux 文件与目录管理全解析
1. 工作目录的切换与保存
在 Linux 系统中,有时需要切换工作目录进行操作,操作完成后再返回原目录。以下是实现该功能的代码示例:
int swd_fd;
swd_fd = open (".", O_RDONLY);
if (swd_fd == -1) {
perror ("open");
exit (EXIT_FAILURE);
}
/* change to a different directory */
ret = chdir (some_other_dir);
if (ret) {
perror ("chdir");
exit (EXIT_FAILURE);
}
/* do some other work in the new directory... */
/* return to the saved directory */
ret = fchdir (swd_fd);
if (ret) {
perror ("fchdir");
exit (EXIT_FAILURE);
}
/* close the directory's fd */
ret = close (swd_fd);
if (ret) {
perror ("close");
exit (EXIT_FAILURE);
}
上述代码通过 open 函数打开当前目录获取文件描述符,使用 chdir 切换到指定目录,操作完成
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



