1.写一个日志文件,将程序启动后,每一秒的时间写入到文件中
#include <myhead.h>
#include <unistd.h>
int main()
{
//定义文件指针
FILE *fp = NULL;
if ((fp = fopen("./time.txt", "w")) == NULL)
{
//strerror:将错误吗转变为错误信息
printf("errno:%s\n", strerror(errno));
return -1;
}
int count = 0;
while (count != 10)
{
//定义变量储存描述
time_t sys_time = time(NULL);
//将秒数转换为结构体
struct tm *time_ptr = localtime(&sys_time);
char buf[128] = "";
snprintf(buf, sizeof(buf), "%4d-%2d-%2d %2d:%2d:%2d\n",
time_ptr->tm_year + 1900,
time_ptr->tm_mon + 1,
time_ptr->tm_mday,
time_ptr->tm_hour,
time_ptr->tm_min,
time_ptr->tm_sec);
printf("buf=%s\n", buf);
fwrite(buf, strlen(buf), 1, fp); //单字符吸入
count++;
sleep(1);
}
fclose(fp);
return 0;
}
2.使用fread、fwrite完成两个文件的拷贝
#include <myhead.h>
int main(int argc, const char *argv[])
{
//判断传入的是否为三个文件
if (argc != 3)
{
printf("input file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
//以只读的形式打开源文件
FILE *sfp = NULL;
if ((sfp = fopen(argv[1], "r")) == NULL)
{
printf("open src file error\n");
return -1;
}
//以只写的形式打开目标文件
FILE *dfp = NULL;
if ((dfp = fopen(argv[2], "w")) == NULL)
{
printf("open destfile error\n");
return -1;
}
// 读取文件内容
char buf[128];
int res;
while ((res = fread(buf, 1, sizeof(buf), sfp)) > 0) // 检查res是否大于0
{
fwrite(buf, 1, res, dfp);
}
fclose(sfp);
fclose(dfp);
return 0;
}