linux编程初试

spring 1年前 ⋅ 344 阅读

今天的java项目搞了一个下午,后来发现是一个小问题纠结了很长时间,悲剧。

刚刚12点,睡不着,就练习下linux编程吧,前段时间买了本《linux程序设计》,感觉挺好的,就随便看看。

照着例题敲了下,顺便总结下:

例程在P104,扫描目录。

本程序的目的是扫描一个目录,并且把目录下的内容输出出来,主要操作在printdir函数内完成。

DIR是一个目录流结构体,在dirent.h头文件中声明,目录流指针(DIR *)被用来完成各种目录操作,其使用方法与普通文件流指针(
FILE *)很相似,目录数据项在dirent结构体中返回,用户不能更改DIR中的字段。dirent结构题中包括d_ino表示文件的inode节点号,表示文件名的name等等,其相应的操作有:

DIR *opendir( const char *name );

/*打开目录失败时返回空指针,打开目录过多可能会失败*/

struct dirent *readdir( DIR *dirp );

/*到达DIR末尾时返回NULL,不改变errno的值*/

long int telldir( DIR *dirp );

/*返回值记录目录流当前位置,返回值可以用seekdir重置位置*/

void seekdir( DIR *dirp, long int loc );

/*重置dirp到loc位置*/

int closedir( DIR *dirp );

/*关闭目录流,成功时候返回0*/

 

printdir函数刚开始时候判断dir是不是能打开,如果打不开就跳出当前函数。

chdir会使程序切换到dir目录。

在while循环中每次从目录流中读出一个dirent,并且跳过.和..,如果是文件则输出文件名,如果是目录则输出目录名并递归输出这个目录。通过depth控制缩排,使输出更有层次感。

 

#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

void printdir(char *dir, int depth ){
DIR *dp;
struct dirent *entry;
struct stat statbuf;

if( (dp=opendir(dir)) == NULL ){
fprintf(stdout,"cannot open directory: %s\n",dir);
return ;
}

chdir(dir);

while( (entry=readdir(dp)) != NULL ){
lstat(entry->d_name,&statbuf);
if( S_ISDIR( statbuf.st_mode ) ){
/* Found a directory, but ignore . and .. */
if( strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0 )
continue;

printf("%*s%s/\n",depth,"",entry->d_name);
printdir(entry->d_name,depth+4);
}
else
printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}

int main(void){
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done\n");
return 0;
}

stat结构中会保存文件的状态信息,其中包含了文件权限和类型信息,
UID,GID,访问时间(atime,ctime,mtime)等等。这个程序用到了stat中的st_mode和与之相关联的宏。st_mode包含了文件权限和类型信息,用sys/stat.h中的宏S_ISDIR判断判断st_mode可以知道数据是不是目录。

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: