linux下的高級文件編程

測試文件類型

#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;
}
        



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章