文件IO 12.12

1.用read write函数实现文件拷贝

#include "head.h"



int main(int argc, const char *argv[])
{
	umask(0);
	int fd1=open("./1211.c",O_RDONLY);
	int fd2=open("./open2.txt",O_RDWR|O_CREAT,0777);
	if(fd1<0||fd2<0)
	{
		perror("open");
		return -1;
	}
	char buf[128]="";
	ssize_t res=0;
	while((res=read(fd1,buf,sizeof(buf)))!=0)
	{
		write(fd2,buf,res);
		memset(buf,0,sizeof(buf));
	}

	close(fd1);
	close(fd2);
	return 0;
}


2.更新任务:要求将当前路径下,所有文件的权限及最后- -次的访问时间提取出来,写入到file.txt中! !

#include "head.h"


int main(int argc, const char *argv[])
{
	FILE* fp=fopen("./file.txt","w+");
	if(NULL==fp)
	{
		perror("fopen");
		return -1;
	}
	DIR *p1=opendir("./");
	if(NULL==p1)
	{
		perror("opendir");
		return -1;
	}

	struct dirent *p2=NULL;
	struct stat p3;
	time_t t;
	struct tm* info=NULL;
	while(1)
	{
		p2=readdir(p1);
		if(NULL == p2)
		{
			break;
		}
		char *prr=p2->d_name;
		if(stat(prr,&p3))
		{
			perror("stat");
			return -1;
		}
		t=p3.st_ctime;
		info=localtime(&t);
		int a=p3.st_mode&0777;
		fprintf(fp,"文件名:%s   mode:%o   ",p2->d_name,a);
		fprintf(fp,"time:%d-%02d-%02d %02d:%02d:%02d\n",info->tm_year+1900,\
				info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
		
	}
	return 0;
}

运行结果:


3.自己封装-个head.h头文件,可以将目前所有的头文件集成到head.h中,然后将head. h移动到/usr/include/文件夹中

#ifndef __HEAD_H__
#define __HEAD_H__

#include "stdio.h"
#include "unistd.h"
#include "string.h"
#include "stdlib.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "math.h"
#include "time.h"
#include "dirent.h"

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值