1、用read write实现文件拷贝
//用read write实现文件拷贝
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
//将head.h拷贝到1.txt文件中
int main(int argc, char const *argv[])
{
int fd1 = open("./head.h", O_RDWR|O_CREAT|O_APPEND, 0775);
if(fd1 < 0)
{
perror("open");
return -1;
}
int fd2 = open("./1.txt", O_RDWR|O_CREAT|O_APPEND, 0775);
if(fd2 < 0)
{
perror("open");
return -1;
}
char c;
ssize_t res = 0;
while(1)
{
res = read(fd1, &c, sizeof(c));
if(0 == res)
break;
write(fd2, &c, sizeof(c));
}
close(fd1);
close(fd2);
return 0;
}
2、更新任务:要求将当前路径下,所有文件的权限及最后一次的访问时间提取出来,写入到file.txt中! !
//将当前文件夹的所有文件的权限,以及最后一次访问时间写入文件file.txt中
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char const *argv[])
{
DIR *dp = opendir("./");
if(NULL == dp)
{
perror("opendir");
return -1;
}
FILE *fp = fopen("./file.txt", "w+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
struct dirent* dir = NULL;
struct stat buf;
struct tm *info = NULL;
int t[4] = {0};
int i = 0;
while(1)
{
dir = readdir(dp);
if(NULL == dir)
{
break;
}
stat(dir->d_name, &buf);
info = localtime(&buf.st_ctime);
fprintf(fp, "%-10s\t%o\t", dir->d_name, buf.st_mode & 0777);
t[0] = info->tm_mon+1;
t[1] = info->tm_mday;
t[2] = info->tm_hour;
t[3] = info->tm_min;
fprintf(fp, "%d %02d %02d:%02d\n", t[0], t[1], t[2], t[3]);
}
fclose(fp);
closedir(dp);
return 0;
}