step4 . day2标准IO和文件IO 小测试demo

为了熟练一下各种函数,练习两个小demo,练习新的就是记住函数名字和功能就行,剩下的细节查man手册(多年学的英语单词终于用到实处了,背单词真有用!!)

1.行数查询


#include <stdio.h>
#include <string.h>
#define N 32

int main(int argc, const char *argv[])
{
if(argc < 2){
printf("Usrmsg:%s <file_name>\n",argv[0]);
return -1;
}
FILE *fp;
if((fp = fopen(argv[1],"r")) == NULL){
perror("fopen");
return -1;
}
int line = 0;
char buf[N];
while((fgets(buf,N,fp)) != NULL){
if(buf[strlen(buf)-1] == '\n')
line++;
}
printf("line in %s are %d\n",argv[1],line);
fclose(fp);
return 0;

}

2.时间log记录


#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define N 64
int main(int argc, const char *argv[])
{
FILE *fp;
int line = 0;
time_t t;
struct tm *lt;
char buf[N];


if((fp = fopen("time.txt","a+")) == NULL){
perror("fopen");
return -1;
}

while(fgets(buf,N,fp) != NULL){
if(buf[strlen(buf)-1] == '\n'){ line++;}
}
while(1){
time(&t);
lt = localtime(&t);
fprintf(fp,"%02d,%d-%02d-%02d %02d-%02d-%02d\n",++line,lt->tm_year+1900,
lt->tm_mon+1,lt->tm_mday,lt->tm_hour,lt->tm_min,lt->tm_sec);
sleep(1);
fflush(fp);
}

return 0;
}

猜你喜欢

转载自www.cnblogs.com/huiji12321/p/11293707.html
今日推荐