write 、read实现文件拷贝
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fd1 = open("./01_getdtablesize.c", O_RDONLY);
if(fd1<0)
{
perror("open");
return -1;
}
int fd2 = open("./open.txt",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd2<0)
{
perror("open");
return -1;
}
char buf1[128]="";
ssize_t res = 0;
while(1)
{
res = read(fd1,buf1,sizeof(buf1)-1);
if(res == 0)
{
break;
}
write(fd2,buf1,res);
}
close(fd1);
close(fd2);
return 0;
}
2、更新任务:要求将当前路径下,所有文件的权限及最后一次的访问时间提取出来,写入到file.txt中!
#include <stdio.h>
#include <myhead.h>
int main(int argc, const char *argv[])
{
//打开file.txt文件
FILE* fp =fopen("./file.txt","w+");
if(fp<0)
{
perror("open");
return -1;
}
DIR* dp = opendir("./");
if(NULL == dp)
{
perror("opendir");
return -1;
}
struct dirent* rp = NULL;
struct stat buf;
struct tm *info = NULL;
while(1)
{
if(NULL == rp )
{
break;
}
stat(rp->d_name,&buf);
info = localtime(&buf.st_ctime);
fputs(rp->d_name,fp);
fputs(buf.st_mode & 0777,fp);
fprintf(fp,"%d-%d %d:%d:%d\r",\
info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
fflush(stdout);
}
fclose(fp);
closedir(dp);
return 0;
}