1. 要求创建一个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>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
FILE* fp = fopen("./time.txt","a+");
if(NULL == fp)
{
MSG_ERR("fopen");
return -1;
}
printf("fopen success\n");
char c;
int line=1;
while((c=fgetc(fp))!=-1)
{
if(c==10)
line++;
}
time_t t;
//time(&t);
struct tm* info = NULL;
while(1)
{
t = time(&t);
info = localtime(&t);
fprintf(fp,"[%02d] %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);
fflush(fp);
sleep(1);
}
if(fclose(fp) < 0)
{
MSG_ERR("fclose");
return -1;
}
printf("fclose success\n");
return 0;
}
测试结果
2. 要求文件IO拷贝一张图片; eog ***.png
完整代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
int fd_r = open("/home/ubuntu/Pictures/1.png",O_RDONLY);
int fd_w = open("./copy.png",O_RDWR|O_CREAT|O_TRUNC,0777);
if(fd_r<0)
{
MSG_ERR("open");
return -1;
}
if(fd_w<0)
{
MSG_ERR("open");
return -1;
}
char arr[100] = "";
ssize_t res;
while((res=read(fd_r,arr,100))>0)
{
write(fd_w,arr,res);
bzero(arr,sizeof(arr));
}
close(fd_r);
close(fd_w);
return 0;
}
测试结果
3. 附加:用标准IO拷贝一张图片
完整代码
#include <stdio.h>
#include <string.h>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
FILE* fp_r = fopen("/home/ubuntu/Pictures/1.png","r");
if(NULL==fp_r)
{
MSG_ERR("fopen");
return -1;
}
FILE* fp_w = fopen("./2.png","w+");
if(NULL==fp_w)
{
MSG_ERR("fopen");
return -1;
}
char c;
while(fread(&c,1,1,fp_r)!=0)
{
fwrite(&c,1,1,fp_w);
}
fclose(fp_r);
fclose(fp_w);
return 0;
}