要求文件IO拷贝一张图片; eog 4.png
图片原地址

把图片拷贝到当前文件中

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc, const char *argv[])
{
//打开图片
int fd_r = open("../../../图片/1.jpg",O_RDONLY);
if(fd_r < 0)
{
printf("%d\t",__LINE__);
perror("open");
return -1;
}
int fd_w = open("copy.jpg",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd_w < 0)
{
printf("%d\t",__LINE__);
perror("open");
return -1;
}
//开始打印
char buf[2];
while(1)
{
ssize_t res = read(fd_r,buf,sizeof(buf));
if(0 == res)
break;
write(fd_w,buf,res);
}
//关闭文件
close(fd_w);
close(fd_r);
return 0;
}
要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08
ctrl + c退出程序,过一会儿之后重新启动程序
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <-------------------
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32

#include<stdio.h>
#include<time.h>
#include<unistd.h>
int sum(FILE *fp)
{
int i=0;
int sum=0;
char c;
while(1)
{
size_t res=fread(&c,1,1,fp);
i++;
if(c == '\n')
sum++;
if(0 == res)
break;
}
return sum;
}
int main(int argc, const char *argv[])
{
//打开/创建文件
FILE *fp = fopen("./time.txt","a+");
if(NULL == fp)
{
printf("%d",__LINE__);
perror("fopen");
return -1;
}
//时间
int i=0;
time_t t;
struct tm *info = NULL;
//遍历源文件行数
i=sum(fp);
while(1)
{
//刷新时间
t = time(NULL);
info = localtime(&t);
//
fprintf(fp,"[%d]%d-%02d-%02d %02d:%02d:%02d\n",i,info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
i++;
fflush(fp);
sleep(1);
}
//关闭文件
fclose(fp);
return 0;
}
7万+

被折叠的 条评论
为什么被折叠?



