step4 . day2标准IO和文件IO 小测试demo
為了熟練一下各種函數(shù),練習(xí)兩個(gè)小demo,練習(xí)新的就是記住函數(shù)名字和功能就行,剩下的細(xì)節(jié)查man手冊(cè)(多年學(xué)的英語(yǔ)單詞終于用到實(shí)處了,背單詞真有用!!)
1.行數(shù)查詢
#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.時(shí)間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;
}
轉(zhuǎn)載于:https://www.cnblogs.com/huiji12321/p/11293707.html
總結(jié)
以上是生活随笔為你收集整理的step4 . day2标准IO和文件IO 小测试demo的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: step4 . day1标准IO和文件I
- 下一篇: js中json的创建和解析