Linux文件操作

文件操作

Linux文件结构

系统调用

库函数

底层文件访问

库函数

底层文件访问

标准I/O库

格式化输入和输出

文件和目录的维护

扫描目录

opendir函数

打开一个目录并建立一个目录流。如果成功,它返回一个指向DIR结构的指针,该指针用于读取目录数据项。
opendir在失败时返回一个空指针。
注意,目录流使用一个底层文件描述符来访问目录本身,所以打开的文件过多,opendir可能会失败。

     #include <dirent.h>
     #include <sys/types.h>
     
     DIR *opendir(consrt char *name)
    readdir()
    telldir()
    seekdir()
    closedir()
#include <stdio.h> 
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>

#include <sys/stat.h>

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

	if((dp = opendir(dir)) == NULL ){
		fprintf(stderr,"cannot open directory : %s\n" , dir);
		return ;
	}
	
	chdir(dir);
	while((entry = readdir(dp)) !=  NULL){
	 /*lstat(const char *path , struct stat *buf)获得一个与此命名文件有关的信息(到一个struct stat 类型的buf中)*/
		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);	
			//Recurse at a new indent level
			printdir(entry -> d_name ,depth +4);		
		}
		else printf("%*s%s\n",depth,"",entry->d_name);	
		
	}
	chdir("..");		//chdir()用户当前的工作目录改变成以参数路径所指的目录
	closedir(dp);

}

void chmdtxt(char *path ){
	
	int cd;	
	cd = chmod(path, S_IRUSR | S_IWUSR | S_IRGRP);	

	printf("done!\n");
}


int main(){
	char add[100];
gantt

	printf("Directory scan of: \n");
	scanf("%s", add);
	printdir(add,0);
	printf("\ndone!\n");

	chmdtxt("/home/crowds/1.txt");

	exit(0);

}

错误处理

/proc文件系统

高级主题fcnt1和mmap

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值