1.要求创建一个time.txt,存储时间格式
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int file_line(FILE *fp)
{
if(NULL == fp)
{
perror("fopen");
return -1;
}
int count = 0;
char c;
while((c=fgetc(fp))!=-1)
{
if(c=='\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
FILE* fp = fopen("./time.txt","a+");
if(NULL == fp)
{
perror("open");
return -1;
}
time_t t;
struct tm *info;
int line = file_line(fp) + 1;//获取行号
while(1)
{
t = time(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);
printf("已写入%d行\r",line);
line++;
fflush(fp);
fflush(stdout);
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 fd_r = open("./1.jpg",O_RDONLY);
if(fd_r < 0)
{
MSG_ERR("open");
return 1;
}
int fd_w = open("./2.jpg",O_RDWR|O_CREAT|O_TRUNC,0660);
if(fd_w < 0)
{
MSG_ERR("open");
return -1;
}
char c;
int res;
while(1)
{
res = read(fd_r,&c,sizeof(c));
if(res==0)
{
break;
}
write(fd_w,&c,res);
}
printf("图片复制成功\n");
return 0;
}