嵌入式学习-IO进程线程-Day1
一、思维导图
二、作业
1.使用fgets统计一个文件的行号
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *srcfp;//定义文件指针
if(argc!=2)//判断外部传参个数
{
printf("input file error\n");
return -1;
}
int count=0;
char buf[10]=""; //定义一个字符串搬运工
srcfp=fopen(argv[1],"r");//只读的方式打开终端输入的文件
if(srcfp==NULL)
{
perror("fopen error");
return -1;
}
while(1)
{
char *res=fgets(buf,sizeof(buf),srcfp);
if(res==NULL) //为空 跳出循环
break;
if(buf[strlen(buf)-1]=='\n')//数组长度的前一位是换行则计数加
count++;
}
printf("count=%d\n",count);
//关闭文件
fclose(srcfp);
return 0;
}
运行结果
2.使用fgets、fputs完成两个文件的拷贝
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *srcfp=NULL,*dstfp=NULL;
if(argc!=3)//判断外部传参的个数
{
printf("input file error\n");
printf("usage: ./a.out srcfile dstfile\n");
return 0;
}
if((srcfp=fopen(argv[1],"r"))==NULL)//以只读的形式打开源文件
{
perror("srcfile open error");
return -1;
}
if((dstfp=fopen(argv[2],"w"))==NULL)//以只写的形式打开目标文件
{
perror("dstfile open error");
return -1;
}
char buf[10]="";//定义一个字符搬运工
while(1)
{
char *res=fgets(buf,sizeof(buf),srcfp);
if(res==NULL)//为空则跳出循环
break;
else //将数组中的内容写入目标文件
fputs(buf,dstfp);
}
printf("拷贝成功\n");
//关闭文件
fclose(srcfp);
fclose(dstfp);
return 0;
}
}
运行结果
3.向文件中输出当前的系统时间
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<time.h>
int get_line(FILE *fp)
{
//读物文件中的内容
char buf[10] = "";
int count = 0; //记录行号
while(1) //循环读取
{
char * res = fgets(buf, sizeof(buf), fp); //读取一个字符串
if(res == NULL) //判断是否读取结束
{
break;
}
//判断最后一个字符是否为'\n'
if(buf[strlen(buf)-1] == '\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
time_t old_time,new_time;
struct tm* t;
char buf[128]="";
FILE *fp=fopen("./time.txt","a+");
if(fp==NULL)
return -1;
int line=get_line(fp);
while(1)
{
time(&new_time);
if(old_time!=new_time)
{
old_time=new_time;
t=localtime(&old_time);
sprintf(buf,"%d.%4d-%02d-%02d %02d:%02d:%02d\n",\
line++,t->tm_year+1900,t->tm_mon+1,t->tm_mday,\
t->tm_hour,t->tm_min,t->tm_sec);
fputs(buf,fp);
fflush(fp);
}
}
fclose(fp);
return 0;
}
运行结果