1、P103
一个目录扫描程序。
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
int isAdir(char* path); //判断路径是否是目录类型
void printdirs(char* path,int depth) //递归遍历打印文件与目录名
{
DIR* dir=opendir(path);
struct dirent* dirents;
chdir(path);
while(dirents=readdir(dir))
{
if(isAdir(dirents->d_name))
{
if(strcmp(".",dirents->d_name)==0||strcmp("..",dirents->d_name)==0)
continue;
printf("%*s%s/ \n",depth," ",dirents->d_name);
printdirs(dirents->d_name,depth+1);
}
else
printf("%*s%s/ \n",depth," ",dirents->d_name);
}
chdir("..");
closedir(dir);
}
int isAdir(char* path)
{
struct stat statbuff;
//printf("%s",path);
lstat(path,&statbuff);
if(S_ISDIR(statbuff.st_mode))
{
return 1;
}
return 0;
}
int main(int argc,char* argv[])
{
/* char* path[1023];
gets(path); //用户在程序中自己输入的Path
chdir(path);*/
char* path="."; //用程序的参数当path
if(argc >=2)
{
path = argv[1];
}
if(isAdir(path)==1)
{
printdirs(path,0);
perror("wrong::");
return 1;
}
printf("path is not a dir");
return 1;
}
2、P112
使用mmap函数程序,来修改文件内容,将文件映射到内存,并且看成数组进行更改!
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/mman.h>
#define recordNum (50)
struct Record //记录的结构
{
int integ;
char string[15];
}Record;
int creatfile(char* file)
{
struct Record r;
FILE* fp=fopen(file,"w+");
int i=0;
for(;i<50;i++)
{
r.integ=i;
memset(r.string,0,15);
sprintf(r.string,"Record-%d",i); //格式化字符串输入到r.string中
fwrite(&r,sizeof( r),1,fp);
}
fclose(fp);
}
void memomap(char* file)
{
struct Record rECORD,*r;
int f=open(file,O_RDWR);
r=(struct Record *)mmap( 0 , recordNum*sizeof(struct Record), PROT_READ|PROT_WRITE, MAP_SHARED , f,0); //内存映射函数
r[20].integ=100;
sprintf(r[20].string,"Record-%d",r[20].integ);
msync((void*)r,recordNum*sizeof(rECORD),MS_SYNC); //将该内存段的修改保存回文件中
munmap((void*)r,recordNum*sizeof(rECORD)); //释放内存段
close(f);
return;
}
int main(int argc,char* argv[])
{
creatfile("records.date");
memomap("records.date");
return 1;
}