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; }
相关文章推荐
- Linux高级编程复习 第四章 IO 文件映射 文件描述符 curses字符界面
- Linux环境高级编程:文件IO
- 关于Unix/Linux之Inode之我见----------Unix环境高级编程--目录、文件
- Linux-C高级编程(1)文件操作(一)
- Linux高级编程--05.文件读写
- (Linux高级编程)读写文件
- Linux-C高级编程(1)文件操作(二)
- Linux下C语言高级编程必备!(附多文件编程代码)
- Linux高级文件编程 标准C部分笔记
- linux标准文件编程库(高级文件编程)
- 文件和目录 - UNIX环境高级编程-第4章
- linux编程--获取文件状态与文件映射mmap .
- unix环境高级编程-文件长度与截断
- UNIX环境高级编程学习之第六章系统数据文件和信息-GID To GroupName
- Unix环境高级编程中头文件apue.h的问题
- 【Linux系统编程】Linux 可执行文件结构与进程结构
- Linux下系统调用文件编程整理
- 学习 Linux高级编程09_A
- unix环境高级编程 err文件
- linux系统编程之文件与io(四)