1
问题:记录时间
代码
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<time.h>
#define PER(per) { fprintf(stderr,"line:%d ",__LINE__);\
perror(per);\
return -1;}
int main(int argc, const char *argv[])
{
//打开文件,以追加的方式
FILE *fp=fopen ("./time.txt","a+");
if(fp==NULL)
{
PER("open");
}
//修改文件偏移量到开头
fseek(fp, 0, SEEK_SET);
int i=0;
//获取偏移量
int a;
do
{
a=fgetc(fp);
if(a==EOF)
{
break;
}
i++;
}while(a!=10);
//修改文件偏移量
fseek(fp,-1*i,SEEK_END);
//判断开始号码
int num;
int res=fscanf(fp,"[%4d]",&num);
if(res<0)
{
num=0;
}
//修改文件偏移量回结尾
fseek(fp, 0, SEEK_END);
while(1)
{
num++;
//计算时间
time_t t=time(NULL);
struct tm* info=localtime(&t);
//写入时间
fprintf(fp,"[%4d]:%d-%02d-%02d %02d:%02d:%02d\n",num,info->tm_year+1900,info->tm_mon+1,info->tm_mday,
info->tm_hour,info->tm_min,info->tm_sec);
sleep(1);
fflush(fp);
}
//关闭文件
if(fclose(fp)==EOF)
{
PER("close");
}
return 0;
}
2
问题 文件IO拷贝一张图片;
代码
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define PER(per){fprintf(stderr,"line: %d ",__LINE__);\
perror("open");\
return -1;}
int main(int argc, const char *argv[])
{
//打开图片文件
int fd_r=open(argv[1],O_RDONLY);
if(fd_r<0)
{
PER("open");
}
//打开目标文件
int fd=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0775);
if(fd<0)
{
PER("open");
}
char a[20]="";
int res;
while(1)
{
bzero(a,sizeof(a));
res = read(fd_r, a, sizeof(a));
if(0 == res)
break;
write(fd, a, res);
}
//关闭文件
close(fd_r);
close(fd);
return 0;
}
#2.
问题:用标准IO拷贝一张图片
代码
#include<stdio.h>
#include <string.h>
#define PER(per){fprintf(stderr,"line: %d ",__LINE__);\
perror("open");\
return -1;}
int main(int argc, const char *argv[])
{
//打开图片文件
FILE *fp_r=fopen(argv[1],"r");
if(fp_r==NULL)
{
PER("open");
}
//打开目标文件
FILE* fp=fopen(argv[2],"w+");
if(NULL==fp)
{
PER("open");
}
char a;
size_t res;
while(1)
{
res = fread( &a, sizeof(a),1,fp_r);
if(0 == res)
break;
fwrite( &a,res,1,fp);
}
//关闭文件
fclose(fp_r);
fclose(fp);
return 0;
}