1. 使用fread和fwrite完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 10
FILE* open_file(char name[], char mode[])
{
FILE* fp = NULL;
if ((fp = fopen(name, mode)) == NULL)
{
return NULL;
}
return fp;
}
int main(int argc, char const *argv[])
{
FILE* src = open_file("pm.bmp", "r");
if (NULL == src)
{
perror("fopen error");
return -1;
}
FILE* dest = open_file("pm2.bmp", "w");
if (NULL == dest)
{
perror("fopen error");
return -1;
}
int len = 0;
char buf[MAXSIZE];
while ((len = fread(buf, 1, sizeof(buf), src)) != 0)
{
fwrite(buf, 1, len, dest);
}
fclose(src);
fclose(dest);
return 0;
}
2. 使用read和write完成两个文件的拷贝
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#define MAXSIZE 1024
int main(int argc, char const *argv[])
{
int src = -1;
if((src = open("pm.bmp", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
int dest = -1;
if((dest = open("pm2.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<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#define MAXSIZE 32
void write_time(int fd, struct tm* t, int* count)
{
// 格式化内容并写入到文件
char time_buf[MAXSIZE];
snprintf(time_buf, sizeof(time_buf), "%d, %2d:%2d:%2d\n", (*count)++, t->tm_hour, t->tm_min, t->tm_sec);
write(fd, time_buf, strlen(time_buf));
}
int main(int argc, char const *argv[])
{
int fd = -1;
if((fd = open("test.txt", O_RDWR|O_APPEND|O_CREAT)) == -1)
{
perror("open error");
return -1;
}
// 获取最后一行的行号,若最后一行不存在则认为是从头开始
int count = 0;
lseek(fd, -20, SEEK_END);
char count_buf[15];
int len = read(fd, count_buf, sizeof(count_buf));
if (len == -1 || len == 0)
{
count = 1;
}
else
{
int i = 0;
while (count_buf[i] != '\n')
{
i++;
}
i++;
while (count_buf[i] != ',')
{
count = count * 10 + count_buf[i] - '0';
i++;
}
count++;
}
// sec为上一刻时间秒数,t->tm_sec为此刻时间秒数,若相同则跳过,若不同则更新sec并将此刻时间写入文件
time_t sysTime = time(NULL);
struct tm* t = localtime(&sysTime);
write_time(fd, t, &count);
int sec = t->tm_sec;
while (1)
{
sysTime = time(NULL);
t = localtime(&sysTime);
if (t->tm_sec != sec)
{
printf("%d\n", t->tm_sec);
sec = t->tm_sec;
write_time(fd, t, &count);
}
}
close(fd);
return 0;
}
屏幕录制 2024-02-19 190532