Day1
思维导图
作业
使用fgets统计一个文件的行号
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
fp=fopen("./1.c","r");
char buf=0;
int count=0;//统计
while(1)//循环
{
buf=fgetc(fp);
if(buf == '\n')
count++;
if(buf==EOF)//循环结束条件
break;
}
printf("%d\n",count);
fclose(fp);//关闭文件
return 0;
}
运行结果
使用fgets、fputs完成两个文件的拷贝
代码
#include<stdio.h>
int main(int argc, const char *argv[])
{
//判断外部传参的个数
if(argc != 3)
{
printf("input file error\n");
printf("usage:./a.out srcfile destfile\n");
return 0;
}
//定义两个指针,分别指向源文件和目标文件
FILE *srcfp, *destfp;
//以只读的形式打开源文件
if((srcfp = fopen(argv[1], "r")) == NULL)
{
perror("srcfile open error");
return -1;
}
//以只写的形式打开目标文件
if((destfp = fopen(argv[2], "w")) == NULL)
{
perror("destfile open error");
return -1;
}
//定义一个字符搬运工
char buf = 0;
while((buf = fgetc(srcfp)) != EOF)
{
//将从源文件中读取的字符写入到目标文件
fputc(buf, destfp);
}
//关闭两个文件
fclose(srcfp);
fclose(destfp);
printf("拷贝成功\n");
return 0;
}
运行结果
向文件中输出当前的系统时间
代码
#include<stdio.h>
#include<time.h>
int main(int argc, const char *argv[])
{
while(1)
{
//定义一个时间类型的变量,存储秒数
time_t sys_time = 0;
//调用时间函数,获取秒数
time(&sys_time);
//将秒数转变成时间结构体类型
struct tm* t = localtime(&sys_time);
char buf[128] =""; //存储格式串的容器
sprintf(buf,"%4d-%02d-%02d %02d:%02d:%02d",t->tm_year+1900, t->tm_mon+1,\
t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);//将年月日,时分秒存入buf
printf("buf = %s\n", buf);//输出buf
sleep(1);
}
return 0;
}
运行结果