作业1:
主函数:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//以写的方式打开文件
FILE* fp = fopen("./time.txt","a+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
//打印时间前先计算行数
int line = 1;
char c;
while((c=fgetc(fp)) != EOF)
{
if(c==10)
line++;
}
time_t t;
struct tm *info = NULL;
//死循环打印时间戳
while(1)
{
t = time(NULL);
info = localtime(&t);
fprintf(fp,"[%d] %d-%02d-%02d %02d:%02d:%02d\n", \
line,info->tm_year+1900, info->tm_mon+1, \
info->tm_mday,info->tm_hour, info->tm_min,\
info->tm_sec);
line++;
fflush(fp);
sleep(1); //一秒打印一次
}
//关闭文件
fclose(fp);
return 0;
}
测试结果:
作业2:
1.主函数:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//文件IO方式打开文件
int fd1 = open("./1.jpeg",O_RDONLY);
int fd2 = open("./2.jpeg",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd1<0||fd2<0)
{
perror("open");
return -1;
}
char buf[50];
ssize_t res = 0;
while(1)
{
bzero(buf,sizeof(buf)); //清空字符串防止写入上个循环的字符串
res = read(fd1,buf,sizeof(buf)); //读取图片数据
write(fd2,buf,res); //写入图片数据
if(0 == res)
break;
}
//关闭文件
if(close(fd1)<0 || close(fd2)<0)
{
perror("close");
return -1;
}
return 0;
}
测试结果:
使用diff验证两个图片文件是否一样:
2.主函数:
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//标准IO打开文件
FILE* fp1 = fopen("./1.jpeg","r");
FILE* fp2 = fopen("./3.jpeg","w");
if(NULL==fp1 || NULL==fp2)
{
perror("fopen");
return -1;
}
char buf[50];
ssize_t res;
while(1)
{
bzero(buf,sizeof(buf)); //清空字符串防止写入上个循环的字符串
res = fread(buf,1,sizeof(buf),fp1); //读取图片数据
fwrite(buf,1,res,fp2); //写入图片数据
if(res==0)
break;
}
//关闭文件
fclose(fp1);
fclose(fp2);
return 0;
}
测试结果:
使用diff验证两个图片文件是否一样: