Linux 系统文件目录操作编程

3.1 文件 IO
【实验内容】
本实验通过一个简单的 copy 程序,完成文件的复制程序,了解基本的文件 I/O 文件读写的基本步骤。
【实验目的】
通过本实验掌握文件 I/O 的基本用法
【实验平台】
PC 机、Ubuntu 操作系统,gcc 等工具
【实验步骤】
编写代码,实现相应的功能
打开源文件
打开目标文件
循环读取源文件并写入目标文件
关闭源文件
关闭目标文件

#include 
#include 
#include 
#include 
#include 
#define maxsize 256 //定义一次从文件读字符的最大数
int main(int argc,char *argv[])
{
int fd1,fd2; //定义源文件和目的文件的文件描述符
char buff[maxsize]; //缓冲
int i;
if(argc!=3) //如果命令格式不正确
{
printf("command error!\n");
return -1;// exit(-1);
Linux 系统实验手册
2
}
fd1=open(argv[1],O_RDONLY); //以只读的方式打开源文件
if(fd1==-1)
{
printf("file %s cannot open",argv[1]);
return -1;//exit(-1);
}
if((fd2=open(argv[2],O_WRONLY|O_CREAT|O_APPEND))==-1)//以追加的方式创建目的文件
{ printf("cannot creat file %s",argv[1]);
return -1;// exit(-1);
}
while(1)
{
i=read(fd1,buff,maxsize);
write(fd2,buff,i);
if(i!=maxsize) break; //如果读到的字节数不是希望的 bufsize,结束文件读写
}
close(fd1);
close(fd2);
}

3.2 目录遍历
【实验内容】
本实验通过一个简单的 ls 程序,完成读目录内容程序,了解基本的读目录读的基本步骤。
【实验目的】
目录读的基本原理与 linux 目录操作的原理
【实验平台】
PC 机、ubuntu 操作系统,gcc 等工具
【实验步骤】
程序代码:

# include 
#include 
#include 
#include  // stat 函数所在的文件
#include 
Linux 系统实验手册
3
int main(void)
{
DIR *dp;
struct dirent *ep;
struct stat st;
char dirp[50];
printf("Please input a dir name:\n");
scanf("%s",&dirp); //读入目录名
dp=opendir(dirp); //打开所给目录
printf("filename:\ttype:\tPermission\taccesstime\tlastmodtime\tsize\t");
if(dp!=NULL) //如果打开目录成功,则进行操作。
{
while(ep = readdir(dp)) //读每一个目录项的循环
{
if(ep->d_name[0]!='.') //判断文件名称的第一个字符是否'.',如果是,表明是隐含文件,我们
不动,否则操作
{//用 stat 函数打开文件的信息,第一个参数是文件的路径,第二个参数存放文件的信息
if(stat(ep->d_name,&st)!=-1) //读成功
{
printf("%s\t",ep->d_name);
if((st.st_mode&S_IFMT)==S_IFDIR) //判断文件的类型
printf("Directory\t"); //目录
else if((st.st_mode&S_IFMT)==S_IFBLK) //块文件
printf("Block special file\t");
else if((st.st_mode&S_IFMT)==S_IFCHR) //特殊字符文件
printf("character special file\t");
else if((st.st_mode&S_IFMT)==S_IFREG) //普通文件
printf("Ordinary file\t");
else if((st.st_mode&S_IFMT)==S_IFIFO) //管道文件
printf("pipefile file\t");
printf("%o\t",st.st_mode&0x1ff); //文件的权限
printf("%15s\t",ctime(st.st_atime)); //文件创建时间
printf("%15s\t",ctime(st.st_mtime)); //文件上次修改时间
printf("%ld\n",st.st_size); //文件的大小
}
}
}
closedir(dp) //关闭目录
}
else
puts("Couldn't open the directory.\n"); //打开不成功时,输出不能打开路径
return 0;
}

你可能感兴趣的:(linux,运维,服务器,嵌入式)