1.使用标准IO完成time.txt
要求创建一个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 <unistd.h>
#include <time.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen("./time.txt","a+");
if(NULL==fp)
{
perror("fopen");
return -1;
}
char a;
int count=1;
while((a=fgetc(fp))!=-1)
{
if(a=='\n')
{
count++;
}
}
time_t t;
struct tm *info=NULL;
while(1)
{
t=time(NULL);
info=localtime(&t);
fprintf(fp,"[%02d] %d-%02d-%02d %02d:%02d:%02d\n", \
count,info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
info->tm_hour, info->tm_min, info->tm_sec);
count++;
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
运行结果
2. 要求文件IO拷贝一张图片
代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.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[])
{
int fd1=open("/home/ubuntu/图片/sllh.jpg",O_RDONLY);
if(fd1<0)
{
MSG_ERR("open");
return -1;
}
int fd2=open("./sllh.jpg",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(fd2<0)
{
MSG_ERR("open");
return -1;
}
char buf[100];
ssize_t c;
while((c=read(fd1,buf,100))>0)
{
write(fd2,buf,c);
}
close(fd1);
close(fd2);
return 0;
}
运行结果
将/home/ubuntu/图片/sllh.jpg复制到当前目录
3. 附加:用标准IO拷贝一张图片
代码
#include <stdio.h>
#define MSG_ERR(msg) do{ \
fprintf(stderr,"line: %d ", __LINE__); \
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
FILE *fp1=fopen("/home/ubuntu/图片/sllh.jpg","r");
if(fp1<0)
{
MSG_ERR("fopen");
return -1;
}
FILE *fp2=fopen("./sllh.jpg","w+");
if(fp2<0)
{
MSG_ERR("open");
return -1;
}
char buf[100];
size_t c;
while((c=fread(buf,1,100,fp1))>0)
{
fwrite(buf,1,c,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
运行结果
将/home/ubuntu/图片/sllh.jpg复制到当前目录