#include <stdio.h>
#include <time.h>
int countLine(const char *fileName){
FILE * fp=NULL;
if((fp=fopen(fileName,"r"))==NULL){
perror("function countLine fopen error");
return -1;
}
char buf[5]="";
char * s=0;
int LineCount=0;
while((s=fgets(buf,sizeof(buf),fp))!=NULL){
int i=0;
while(*(buf+i)!='\0'){
if(*(buf+i)=='\n') LineCount++;
i++;
}
}
//printf("%s line count is %d\n",argv[1],LineCount);
fclose(fp);
return LineCount;
}
int fileCopy(char * srcFileName, char * destFileName){
FILE *sfp=0,*dfp=0;
if((sfp=fopen(srcFileName,"r"))==NULL){
perror("fileCopy source file open error");
return -1;
}
if((dfp=fopen(destFileName,"w"))==NULL){
perror("fileCopy destination file open error");
return -1;
}
char *s=0;
char buf[5]="";
while((s=fgets(buf,sizeof(buf),sfp))!=NULL){
fputs(s,dfp);
}
fclose(dfp);
fclose(sfp);
}
int printDateTimeToFile(char *fileName){
FILE *fp=0;
if((fp=fopen(fileName,"a"))==NULL){
perror("printDateTimeToFile open file error");
return -1;
}
char buf[50]="";
int n=countLine(fileName);
while(1){
time_t sysTime=time(NULL);
struct tm *st_localtime=localtime(&sysTime);
sprintf(buf,"%06d: %4d年%02d月%02d日 %02d:%02d:%02d\n",n++,st_localtime->tm_year+1900,st_localtime->tm_mon+1,st_localtime->tm_mday,st_localtime->tm_hour,st_localtime->tm_min,st_localtime->tm_sec);
sleep(1);
printf("%s\n",buf);
fputs(buf,fp);
fflush(fp);
}
fclose(fp);
return 0;
}
int main(int argc, const char *argv[])
{
if(argc!=2){
printf("error: please enter one file name as argument\n");
return -1;
}
//printf("%s line count is %d\n",argv[1],countLine(argv[1]));
//fileCopy("./a.txt","./c.txt");
printDateTimeToFile("d.txt");
return 0;
}
20231229(IO)作业
于 2024-01-03 09:01:18 首次发布