1.fread和fwrite
代码:
#include <myhead.h>
#define MAXSIZE 64
int main(int argc, char const *argv[])
{
FILE *src = NULL;
FILE *dest = NULL;
if ((src = fopen("./tt1.bmp", "r")) == NULL)
{
perror("fopen error");
return -1;
}
if ((dest = fopen("./tt2.bmp", "w")) == NULL)
{
perror("fopen error");
return -1;
}
char *buf[MAXSIZE];
int res = 0;
while ((res = fread(buf, 1, sizeof(buf), src)) != 0)
{
fwrite(buf, 1, res, dest);
}
fclose(src);
fclose(dest);
return 0;
}
结果:
2.read和write
代码:
#include<myhead.h>
#define MAXSIZE 1024
int main(int argc, char const *argv[])
{
int src = -1;
if((src = open("aa1.bmp", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
int dest = -1;
if((dest = open("aa2.bmp", O_WRONLY|O_CREAT|O_TRUNC, 0664)) == -1)
{
perror("open error");
return -1;
}
int len = 0;
char buf[MAXSIZE];
while((len = read(src, buf, sizeof(buf)))!= 0)
{
write(dest, buf, len);
}
close(src);
close(dest);
return 0;
}
结果:
3.时间在文件中跑起来
代码:
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp = NULL; //文件操作
char buf_time[100] = ""; //时间存储数组
char line[100] = ""; //行数组
char buf[100] = ""; //输出读取
while (1)
{
//以追加可读的方式打开文件
if ((fp = fopen("./systime.txt", "a+")) == NULL)
{
perror("fopen error");
return -1;
}
//1、获取时间的秒数
time_t sysTime = time(NULL);
//2、通过秒数获取时间结构体指针
struct tm *t = localtime(&sysTime);
//循环查找最后一行的行号
int i = 1;
while (fgets(line, sizeof(line), fp) != NULL)
{
i++;
}
//将元素放到数组中
snprintf(buf_time, sizeof(buf_time), "%d,%2d:%2d:%2d\n", i, t->tm_hour, t->tm_min, t->tm_sec);
//将数组写入到文件中
fwrite(buf_time, strlen(buf_time), 1, fp);
//移动光标至读取时间位置
fseek(fp, -strlen(buf_time), SEEK_END);
//输出读取的数据
fread(buf, strlen(buf_time), 1, fp);
printf("%s\n", buf);
sleep(1);
fclose(fp);
}
return 0;
}
结果: