目录
3、标准IO的文件打开方式与文件IO的flag选项的对应关系
1、使用fgets统计文档的行数和大小
#include <stdio.h>
int main(int argc, const char *argv[])
{
char buf[2];
if(argc<2 || argc>2)
{
printf("参数不正确\n");
return -1;
}
FILE *fp_r = fopen(argv[1], "r");
int line = 0;
int data_size = 0;while(1)
{
if(!fgets(buf, 2, fp_r))
{
fprintf(stderr, "文件读取结束或者失败\n");
break;
}
if(buf[0] == '\n')
{
line++;
}
data_size++;
}
printf("%s有%d行,是%d字节.\n", argv[1], line, data_size);fclose(fp_r);
return 0;
}
2、用文档记录时间,并且编号连续
//----------------------------------------------------方法一--------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>int main(int argc, const char *argv[])
{
time_t t;
struct tm *info = NULL;
FILE *fp_time = fopen("./time.txt", "a+");
if(!fp_time)
{
perror("fopen");
return -1;
}char c;
int i = 0;while(1)
{c = fgetc(fp_time);
if( c < 0)
{
break;
}
if('\n' == c)
{
i++;
}
}system("clear");
while(1)
{
i++;
t = time(NULL);
info = localtime(&t);fprintf(fp_time,"[%d] %d-%02d-%02d %02d:%02d:%02d\n",i,\
info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
info->tm_hour,info->tm_min, info->tm_sec);fflush(fp_time);
printf("[%d] %d-%02d-%02d %02d:%02d:%02d\r",i,\
info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
info->tm_hour,info->tm_min, info->tm_sec);fflush(stdout);
sleep(1);
}fclose(fp_time);
return 0;
}//----------------------------------------------------方法二--------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>int main(int argc, const char *argv[])
{
time_t t;
struct tm *info = NULL;
FILE *fp_time = fopen("./time.txt", "a+");
if(!fp_time)
{
perror("fopen");
return -1;
}struct tm tmp;
int i = 0;
while(1)
{
while(1)
{
if(fscanf(fp_time,"[%d] %d-%02d-%02d %02d:%02d:%02d\n", &i, &tmp.tm_year,\
&tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour, &tmp.tm_min\,&tmp.tm_sec) <0 )
{
break;
}
}
i++;
system("clear");
t = time(NULL);
info = localtime(&t);
fprintf(fp_time,"[%d] %d-%02d-%02d %02d:%02d:%02d\n",i,\
info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
info->tm_hour,info->tm_min, info->tm_sec);
fflush(fp_time);
printf("[%d] %d-%02d-%02d %02d:%02d:%02d\r",i,\
info->tm_year+1900, info->tm_mon+1, info->tm_mday,\
info->tm_hour,info->tm_min, info->tm_sec);
fflush(stdout);
sleep(1);
}fclose(fp_time);
return 0;
}