1、使用fgets统计一个文件的行号
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{FILE *fp=NULL;if((fp=fopen("1.c","r"))==NULL){return -1;}int count=0;char buf;while(buf!=EOF){buf=fgetc(fp);if(buf=='\n'){count++;}}printf("%d行\n",count);fclose(fp);return 0;
}
2、使用fgets、fputs3完成两个文件的拷贝
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{if(argc>2){return 0;}FILE *fp1=NULL;FILE *fp2=NULL;//定义两个文件指针,一个读一个写if((fp1=fopen(argv[1],"r"))==NULL){return -1;}if((fp2=fopen(argv[2],"w"))==NULL){return -1;}char buf=0;while((buf=fgetc(fp1))!=EOF){fputc(buf,fp2);}fclose(fp1);fclose(fp2);return 0;
}
3、向文件中输出当前的系统时间.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>
#include<unistd.h>
int main(int argc, const char *argv[])
{while(1){FILE *fp1=NULL;//定义一个数行if((fp1=fopen("time","r"))==NULL){return -1;}//定义一个打印的指针FILE *fp2=NULL;if((fp2=fopen("./time","a"))==NULL){return -1;}char temp;int num=0;while((temp=fgetc(fp1))!=EOF){if(temp=='\n'){num++;}}time_t sys_time;sys_time=time(NULL);struct tm *t=localtime(&sys_time);char buf[100];int sec=t->tm_sec;sprintf(buf,"%02d、%04d-%02d-%02d %02d:%02d:%02d\n",num,t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);fputs(buf,fp2);sleep(1);fclose(fp1);fclose(fp2);}return 0;
}