要求创建一个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退出程序,过一会儿之后重新启动程序
main.c :
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define MSG_error(msg) {\
fprintf(stdout,"line:%d",__LINE__); \
perror(msg);\
return -1; }
int file_line(FILE* fp)
{
int line = 1;
int c = 0;
while((c = fgetc(fp)) != EOF)
{
if('\n' == c)
{
line++;
}
}
return line;
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./time.txt","a+");
if(NULL == fp)
{
MSG_error("fopen");
}
time_t t;
int line = file_line(fp);
while(1)
{
t = time(NULL);
struct tm *info = 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);
fflush(fp);
line++;
sleep(1);
}
fclose(fp);
return 0;
}
要求文件IO拷贝一张图片; eog 4.png
main.c:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define MSG_error(msg) { \
fprintf(stdout,"line:%d",__LINE__);\
perror(msg);\
return -1;\
}
int main(int argc, const char *argv[])
{
int pc1 = open("./1.jpg",O_RDONLY);
if(pc1 < 0)
{
MSG_error("open");
}
int pc2 = open("./copy.jpg",O_RDWR|O_TRUNC|O_CREAT,0777);
if(pc2 < 0)
{
MSG_error("open");
}
char srr[20];
ssize_t res = 0;
while(1)
{
bzero(srr,sizeof(srr));
res = read(pc1,srr,sizeof(srr));
if(0 == res)
{
break;
}
write(pc2,srr,res);
}
if(close(pc1) < 0)
{
MSG_error("close");
}
if(close(pc2) < 0)
{
MSG_error("close");
}
printf("关闭成功\n");
return 0;
}
要求标准IO拷贝一张图片; eog 4.png
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MSG_error(msg) { \
fprintf(stdout,"line:%d",__LINE__);\
perror(msg);\
return -1;\
}
int main(int argc, const char *argv[])
{
FILE* pc1 = fopen("./1.jpg","r");
if(pc1 == NULL)
{
MSG_error("fopen");
}
FILE* pc2 = fopen("./copy2.jpg","w+");
if(pc2 == NULL)
{
MSG_error("fopen");
}
char srr[20];
size_t res = 0;
while(1)
{
bzero(srr,sizeof(srr));
res = fread(srr,sizeof(char),20,pc1);
if(0 == res)
{
break;
}
fwrite(srr,sizeof(char),20,pc2);
}
if(fclose(pc1) < 0)
{
MSG_error("close");
}
if(fclose(pc2) < 0)
{
MSG_error("close");
}
printf("关闭成功\n");
return 0;
}