您的位置:首页 > 运维架构 > Linux

linux下的高级文件编程

2015-05-19 10:42 232 查看
测试文件类型

#include <stdio.h>
#include <sys/stat.h>

int main( int argc, char *argv[] )
{
struct stat statbuf;

if (argc < 2)
{
printf("please input a file paraster\n");
return 1;
}
if ( stat(argv[1], &statbuf) == -1)
{
printf("Can't stat file\n");
return 1;
}
if (S_ISDIR(statbuf.st_mode)){		//目录
printf("is a directory\n");
}else if (S_ISCHR(statbuf.st_mode)){	//特殊文件
printf("is a character special file\n");
}else if (S_ISBLK(statbuf.st_mode)){	//特殊文件块
printf("is a block special file\n");
}else if (S_ISREG(statbuf.st_mode)){	//普通文件
printf("is a regular file\n");
}else if (S_ISFIFO(statbuf.st_mode)){	//特殊FIFO文件
printf("is FILE special file\n");
}else if (S_ISSOCK(statbuf.st_mode)){	//套接字
printf("is a socket\n");
}else{
printf("is unkown\n");
}
return 0;
}


获取文件信息数据

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <langinfo.h>

int main( int argc, char* argv[])
{
struct stat statbuf;
struct passwd *pwd;
struct group *grp;
struct tm *tm;
char tmstr[257];

if (argc < 2)
{
printf("specify is afile to tst\n");
return 1;
}

if (stat(argv[1], &statbuf) == -1)
{
printf(" can't stat file \n");
return 1;;
}

printf( "file size is  %-d\n",statbuf.st_size);

pwd = getpwuid(statbuf.st_uid);
if (pwd != NULL)
printf("file owner is %s\n", pwd->pw_name);

grp = getgrgid(statbuf.st_gid);
if (grp != NULL)
printf("file group is %s\n", grp->gr_name);

tm = localtime(&statbuf.st_mtime);
strftime(tmstr, sizeof(tmstr), nl_langinfo(D_T_FMT), tm);
printf("file date is %s\n", tmstr);

return 0;
}


获取当前工作目录

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
char *pathname;
long  maxbufsize;

maxbufsize = pathconf( ".", _PC_PATH_MAX );
if (maxbufsize == -1) return 1;

pathname = (char *)malloc(maxbufsize);

(void)getcwd( pathname, (size_t)maxbufsize );

printf("%s\n", pathname);

free(pathname);

return 0;
}


列举目录

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
int main( int argc, char* argv[])
{
DIR *dirp;
struct stat statbuf;
struct dirent *dp;
if ( argc < 2)
return 1;
if (stat(argv[1], &statbuf) == -1)
return 1;
if (!S_ISDIR(statbuf.st_mode))
return 1;

while((dp = readdir(dirp)) != NULL)
{
if (stat(dp->d_name,&statbuf) == -1)
continue;
if (!S_ISREG(statbuf.st_mode))
continue;
printf("%s\n",dp->d_name);
}
closedir(dirp);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: