1. 用fgets计算一个文件的大小
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen(argv[1],"r");
if(fp==NULL)
{
perror("fopen");
return -1;
}
char str[50]="";
int byte=0;
while(1)
{
if(fgets(str,sizeof(str),fp)==NULL)
{
break;
}
byte += strlen(str);
}
printf("byte=%d\n",byte);
fclose(fp);
return 0;
}
2. 用fgets计算一个文件有几行;提示:计算一个文件有几个'\n';
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen(argv[1],"r");
if(fp==NULL)
{
perror("fopen");
return -1;
}
char str[100]="";
int line=0;
while(1)
{
if(fgets(str,sizeof(str),fp)==NULL)
{
break;
}
line++;
}
printf("line=%d\n",line);
fclose(fp);
return 0;
}
要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08
ctrl + c退出程序,过一会儿之后重新启动程序
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <-------------------
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int line(FILE *fp);
int main(int argc, const char *argv[])
{
FILE *fp=fopen("./time.txt","a+");
if(fp==NULL)
{
perror("fopen");
return -1;
}
time_t t;
struct tm *info=NULL;
int n=line(fp);
int i=1;
while(1)
{
t=time(NULL);
info=localtime(&t);
fprintf(fp,"[%d] %d-%02d-%02d %02d:%02d:%02d\n",n+i,\
info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
i++;
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
int line(FILE *fp)
{
if(fp==NULL)
{
perror("fopen");
return -1;
}
char ch=0;
int count=0;
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
{
count++;
}
}
return count;
}