1、
1. 用fgets计算一个文件的大小 2. 用fgets计算一个文件有几行;提示:计算一个文件有几个'\n';
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE* fp1=fopen(argv[1],"r");
if(NULL == fp1)
{
perror("fopen");
return -1;
}
char c[20]="";
int s=0;
int m=0;
while(1)
{
if(NULL==fgets(c,sizeof(c),fp1))
{
printf("读完\n");
printf("大小:%d\n",s);
printf("行数:%d\n",m);
fclose(fp1);
break;
}
for(int i=0;i<sizeof(c);i++)
{
if(c[i] != '\0')
{
if(c[i] == '\n')
{
m++;
s++;
break;
}
s++;
}
}
}
return 0;
}
2、要求创建一个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>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
char a;
int s=0;
FILE *fp=fopen("./time.txt","a+");
while((a=fgetc(fp))!=EOF){
if(a == '\n'){
s++;
}
}
time_t t;
struct tm* info;
int i=1;
i=i+s;
FILE *stdout=fopen("./time.txt","a+");
while(1){
t=time(NULL);
info = localtime(&t);
fprintf(stdout,"[%d] "\
"%4d-%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);
i++;
fflush(stdout);
sleep(1);
}
fclose(fp);
fclose(stdout);
return 0;
}
3、