1.用read write函数实现文件拷贝
程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int ph = open("cp.txt",O_WRONLY|O_CREAT|O_TRUNC, 0777);
if(ph < 0)
{
perror("open");
return -1;
}
int ch = open("./01.txt", O_RDONLY);
char a[10] = "";
ssize_t res = 0;
int b = 0;
while(1)
{
res = read(ch, a,sizeof(a)-1);
if(res == 0)
{
break;
}
b = write(ph, a, res);
printf("%s", a);
bzero(a, sizeof(a));
}
close(ph);
close(ch);
}
2.更新任务:要求将当前路径下,所有文件的权限及最后- -次的访问时间提取出来,写入到file.txt中! !
程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
int main(int argc, const char *argv[])
{
// int p = open("./file.txt", O_RDWR|O_CREAT|O_TRUNC);//打开file.txt
FILE * p = fopen("./file.txt", "w");
DIR * dp = opendir("./");//打开当前目录
struct stat b;
ssize_t tav = 0;
long arr = 0;
struct dirent * rp = NULL;
struct tm * info = NULL;
while(1)
{
rp = readdir(dp);
if(rp == NULL)
{
break;
}
printf("%s\n", rp->d_name);
char a[11] = "";
strcpy(a, rp->d_name);
stat(a, &b);
//文件权限
printf("mode: 0%o\n", b.st_mode&0777);
//写入权限
arr = b.st_mode&0777;
// tav = write(p, &arr,sizeof(a));
// printf("tav %ld \n", tav);
fprintf(p, "0%lo\n", arr);
//时间
long d = b.st_ctime;
info = localtime(&d);
printf("%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);
fprintf(p,"%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);
// fprintf(p, "%ld\n",d);
// tav=write(p, &d, sizeof(d)-1);
// printf("tav %ld\n", tav);
printf("\n");
}
return 0;
}
现象