您的位置:首页 > 产品设计 > UI/UE

APUE(4)---文件和目录 (3)

2016-06-30 00:33 393 查看
十三、函数rename和renameat

#include <stdio.h>
int rename(const char *oldname, const char *newname);
int renameat(int oldfd, const char *oldname, int newfd, const char *newname);


  文件或目录可以用rename函数或者renameat函数进行重命名。有几种情况需要说明:

1、如果oldname指的是一个文件而不是目录,那么为该文件或符号链接重命名。在这种情况下,如果newname已存在,它不能引用一个目录。如果newname已存在,而且不是一个目录,则将该目录项删除然后将oldname重命名为newname。对包含oldname的目录以及包含newname的目录,调用进程必须具有写权限。

2、如果oldname指的是一个目录,那么为该目录重命名。如果newname已存在,则它必须引用一个目录,而且该目录应当是一个空目录。

3、如果oldname或newname引用符号链接,则处理符号链接本身,而不是它所引用的文件。

4、不能对.和..重命名。

十四、符号链接及其创建和读取

  符号连接是对一个文件的间接指针,它与硬链接有所不同,硬链接直接指向文件的i节点。引入符号链接的原因是为了避开硬链接的一些限制:1、硬链接通常要求连接和文件位于同一文件系统中;2、只有超级用户才能创建只想目录的硬链接。当使用以名字引用文件的函数时,应当了解该函数是否处理符号链接,也就是该函数是否跟随符号连接到达它所链接的文件。如若该函数具有处理符号连接的功能,则其路径名参数引用由符号连接指向的文件。否则,一个路径名参数引用链接本身,而不是由该连接指向的文件。

#include <unistd.h>
int symlink(const char *actualpath, const char *sympath);
int symlinkat(const char *actualpath, int fd, const char * sympath);

ssize_t readlink(const char *restrict pathname, char *restrict buf, size_t bufsize);
ssize_t readlinkat(int fd, const char *restrict pathname. char *restrict buf, size_t bufsize);


  创建符号连接时,并不要求actualpath已存在,并且,actualpath和sympath并不需要位于同一文件系统中。

十五、文件的时间及其修改

  unix为每个文件维护了三个时间字段:

  st_atim :文件数据的最后访问时间    read        -u

  st_mtim :文件数据的最后修改时间    write        默认

  st_ctim :i节点状态的最后更改时间    chmod、chown   -c

  因为i节点中的所有信息和文件的实际内容是分开存放的。修改时间是文件内容最后一次被修改的时间。状态时间是该文件的i节点一次被修改的时间,我们说明了很多影响到i节点的操作,如更改文件的访问权限、更改用户ID,更改链接数,但是他们并没有修改文件的实际内容。系统并不维护对一个i节点最后一次访问的时间,所以access和stat函数并不更改这3个时间中的任意一个。

  一个文件的访问和修改时间可以用以下几个函数更改:

#include <sys/stat.h>
int futimens(int fd, const struct timespec times[2]);
int utimensat(int fd, const char *path, const struct timespec times[2], int flag);


十六、函数mkdir、mkdirat和rmdir

#include <sys/stat.h>
int mkdir(const char *pathnaem, mode_t mode);
int mkdirat(int fd, const char *pathname, mode_t mode);

#include <unistd.h>
int rmdir(const char *pathname);


  创建空目录会自己创建.和..;常见的错误是制定与文件相同的mode(只指定读、写),但是对于目录通常至少要设置一个执行权限位,以允许访问该目录中的文件名。

十七、读目录

  对某个目录具有访问权限的任一用户都可以读该目录,但是为了防止文件系统产生混乱,只有内核才能写目录。其相关的主要函数:

#include <dirent.h>
DIR *opendir(const char *pathname);
DIR *fdopendir(int fd);

struct dirent * readdir(DIR *dp);

void rewinddir( DIR *dp);

int closedir(DIR *dp);

long telldir(DIR *dp);

void seekdir(DIR *dp, long loc);


  待补充....

十八、函数chdir、fchdir和getcwd

  每个进程都有一个当前工作目录,此目录是搜索所有相对路径名的起点,进程可以调用chdir和fchdir来更改当前目录,需要注意的是当前工作目录是进程的一个属性,所以它只影响调用chdir的金城本身,而不影响其他进程。

#include <unistd.h>
int chdir(const char *pathname);
int fchdir(int fd);

char * getcwd(char *buf, size_t size);


#include "apue.h"

int main(void)
{
char ptr[1024];
size_t size;

if(chdir("/usr/local/lib") < 0)
{
err_sys("chdir error");
}

if(getcwd(ptr, 1024) == NULL)
{
err_sys("getcwd error");
}

printf("cwd = %s\n", ptr);

exit(0);
}


4-23-24 chdir和getcwd实例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: