linux学习:c语言文件操作—读文件
2014-04-25 13:52
453 查看
1、linux下文件操作与其他系统文件操作差异较大,先是创建操作:
2、遍历文件夹
/* ============================================================================ Name : Test.c Author : wangchuan Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(void) { int f; const char *f_path="test"; mode_t f_attrib; struct stat *buf = malloc(sizeof(struct stat)); f_attrib = S_IRUSR | S_IWUSR | S_IWGRP | S_IROTH; f=open(f_path,O_RDONLY); if(f == -1){ f=open(f_path,O_RDWR | O_CREAT,f_attrib); if(f!=-1){ puts("创建一个新文件"); } else{ puts("无法创建新文件"); return 1; } } else puts("文件打开成功"); close(f); stat(f_path,buf); return 0;
2、遍历文件夹
/* ============================================================================ Name : Test.c Author : wangchuan Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <dirent.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> void scan_dir(char *dir,int depth) { DIR *dp; struct dirent *entry; struct stat statbuf; if((dp = opendir(dir)) == NULL){ puts("无法打开该目录"); return; } chdir(dir); while((entry = readdir(dp)) != NULL){ lstat(entry->d_name,&statbuf); if(S_IFDIR & statbuf.st_mode){ if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0) continue; printf("%*s%s/\n",depth,"",entry->d_name); scan_dir(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"); scan_dir("/boot",0); printf("done.\n"); return 0; }
相关文章推荐
- Linux 学习日记 5: 文件系统操作与磁盘管理
- Linux学习笔记之--常用文件操作及目录管理命令
- Linux学习第十五章--文件系统的操作
- Linux学习笔记——常用文件操作命令
- 我的Linux学习笔记1(文件操作常用命令)
- Linux学习之CentOS(四)----Linux文件属性、所有者、群组、其他组及文件权限操作简要总结
- Linux文件操作学习总结【转载】
- linux文件操作学习3
- Linux中C语言文件操作
- linux文件操作学习1
- linux学习笔记一----------文件相关操作
- 实验楼Linux学习笔记(六)之文件系统操作与磁盘管理
- Linux学习7-文件操作
- Linux学习一——文件和目录的基本操作
- Linux学习-文件系统的特殊观察与操作
- Go语言学习(九)文件操作
- Linux学习日记--基础命令(3)-文件操作,通配符,命令别名
- Linux 学习日记 2: 目录结构和文件操作
- linux编程学习--常见文件目录操作
- linux操作系统下c语言编程入门 -- (3)文件操作