IO线程-day2
1> 使用fread和fwrite完成两个文件的拷贝
程序:
#define MAXSIZE 1024
#include<myhead.h>int main(int argc, char const *argv[])
{FILE *srcfp=NULL;FILE *destfp=NULL;if(!(srcfp=fopen("pm.bmp","r")))PRINT_ERR("");if(!(destfp=fopen("pm1.bmp","w")))PRINT_ERR("");char buf[MAXSIZE];int ret=0;while((ret = fread(buf, 1, sizeof(buf), srcfp))!= 0){fwrite(buf, 1, ret, destfp);}fclose(srcfp);fclose(destfp);return 0;
}
结果:
2> 使用read、write完成两个文件的拷贝
程序:
#define MAXSIZE 1024
#include<myhead.h>int main(int argc, char const *argv[])
{int srcfd=-1;int destfd=-1;if(!(srcfd=open("./pm.bmp",O_RDONLY)))PRINT_ERR("");if(!(destfd=open("./pm2.bmp",O_WRONLY|O_CREAT|O_TRUNC,0664)))PRINT_ERR("");char buf[MAXSIZE];int ret=0;while((ret = read(srcfd,buf,sizeof(buf)-1))!= 0){write(destfd,buf,ret);memset(buf,0,sizeof(buf));}close(srcfd);close(destfd);return 0;
}
结果:
3> 将时间在文件中跑起来
程序:
#define MAXSIZE 1024
#include<myhead.h>int linecount(){FILE *fp1=NULL;if(!(fp1=fopen("test.txt","r")))PRINT_ERR("");int line=1;char buf[MAXSIZE];while(1){fgets(buf,sizeof(buf),fp1);for(int i=0;i<strlen(buf);i++){if(buf[i]=='\n')line++;}if(strlen(buf)==0)break;memset(buf,0,sizeof(buf));}fclose(fp1);return line;
}
int main(int argc, char const *argv[])
{int fp = -1;if((fp = open("test.txt", O_WRONLY|O_APPEND|O_CREAT)) == -1){perror("open error");return -1;}time_t sysTime = time(NULL);struct tm* t = localtime(&sysTime);char time_buf[128];snprintf(time_buf, sizeof(time_buf), "%2d、%2d:%2d:%2d\n", linecount(),t->tm_hour, t->tm_min, t->tm_sec);write(fp, time_buf, strlen(time_buf));int sec = t->tm_sec;while (1){sysTime = time(NULL);t = localtime(&sysTime);if (t->tm_sec != sec){printf("%s\n", time_buf);sec = t->tm_sec;snprintf(time_buf, sizeof(time_buf), "%2d、%2d:%2d:%2d\n", linecount(),t->tm_hour, t->tm_min, t->tm_sec);write(fp, time_buf, strlen(time_buf));}}close(fp);return 0;
}
结果:
思维导图: