免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 723 | 回复: 0
打印 上一主题 下一主题

文件操作(二)——linux程序设计之路 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-06 20:49 |只看该作者 |倒序浏览
文件和目录
#include  
int chmod(const char *path,mode_t mode);
int chown(const char *path,uid_t owner,gid_t group)
这两个函数的操作非常简单,特别是熟悉chmod和chown命令。
mode_t的值有:
S_IRUSR,S_IXUSR,S_IWUSR
S_IRGRP,S_IXGRP,S_IWGRP
S_IROTH,S_IXOTH,S_IWOTH
相信大家一看就知道这些个代表的含义吧。
#include
int unlink(const char *path)
int link(const char *path1,const char *path2)
int symlink(const char *path1, const char *path2)
unlink函数用来删除文件的目录项并减少它的链接数,成功返回0,失败返回-1,大家应该知道,linux下一个文件的链接数减少到零,并且没有进程打开它的时候,这个文件才会被删除。
link函数就是ln命令,symlink函数就是ln -s命令。
#include
int mkdir(const char *path,mode_t mode)
和mkdir命令一样,创建一个目录,mode参数和上面介绍的chmod的一样,注意下创建文件指定权限时于umask的关系。
有mkdir函数,则一定有rmdir函数啦
#include
int rmdir(const char *path)
#include
int chdir(const char *path)
char *getcwd(char *buf,size_t size)
cd命令和pwd命令的函数出来了,getcwd把获得的当前目录名字存放在buf中,但是如果目录长度超出了size的长度的时候就会返回NULL。
目录扫描:
用到的函数有:
opendir,closedir,readdir,telldir,seekdir
与目录操作有关的函数都在dirent.h头文件中声明。有个DIR指针和文件操作的FILE指针类似,目录的有关属性保存在dirent结构体中。
下面用一个历程来说明这些函数的操作。
#include unistd.h>
#include sys/stat.h>
#include sys/types.h>
#include stdio.h>
#include stdlib.h>
#include dirent.h>
#include string.h>
void print_dir(char *path,int spaces)
{
    DIR *dp;
    struct dirent *dir;
    struct stat state;
    if((dp=opendir(path))==NULL)
    {
        perror("open dir error");
        exit(1);
    }
    chdir(path);
    while((dir=readdir(dp))!=NULL)
    {
        lstat(dir->d_name,&state);
        if(S_ISDIR(state.st_mode))
        {
            if(!strcmp(dir->d_name,".")||!strcmp(dir->d_name,".."))
                continue;
            printf("%*s%s/\n",spaces,"",dir->d_name);
            print_dir(dir->d_name,spaces+4);
        }
        else printf("%*s%s\n",spaces,"",dir->d_name);
    }
    chdir("..");
    closedir(dp);
}
int main(int argc,char* argv[])
{
    char *path=".";
    if(argc>=2)
        path="argv[1]";
    print_dir(path,0);
    return 0;
}
这是个对目录进行扫描,列出所有项的小程序。
首先用opendir检查目录是否存在,然后用chdir进入该目录,接着读取一个目录,并判断是否是一个文件夹,接着递归调用,最后用closedir关闭目录流并释放相关的资源。
  
  
  
  
   


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/62515/showart_490869.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP