1> 使用fread和fwrite完成两个文件的拷贝,要求源文件和目标文件由外界输入
#include <myhead.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
//以读的形式打开要复制的文件
FILE* rfp = fopen(argv[1],"r");
if(NULL == rfp){
perror("err:");
}
//以写的形式打开复制生成的文件
FILE* wfp = fopen(argv[2],"w");
if(NULL == wfp){
perror("err:");
}
char rarr="";
while(1){
int res = fread(&rarr,1,1,rfp);//循环读取要复制的文件的内容并赋值给ch
if(0 == res)break; //文件读取完毕跳出循环
fwrite(&rarr,1,1,wfp); // 将读取到的文件内容写入到新文件
}
fclose(rfp); //关闭文件描述符
fclose(wfp);
return 0;
}
2> 使用fgets获取当前文件的总行数
#include <myhead.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
//以读的形式打开要复制的文件
FILE* rfp = fopen(argv[1],"r");
if(NULL == rfp){
perror("err:");
}
//以写的形式打开复制生成的文件
FILE* wfp = fopen(argv[2],"w");
if(NULL == wfp){
perror("err:");
}
char rarr[20]=""; //存放读取到的数据
int count = 0; //计算行数
while(1){
char*res = fgets(rarr,sizeof(rarr),rfp);//循环读取要复制的文件的内容
if(res==NULL)break;
if(rarr[strlen(rarr)-1]=='\n'){ //遇到换行符,count++,统计行数
count++;
// rarr[strlen(rarr)-1] = 0;
}
fputs(rarr,wfp);//将读取到的文件内容写入到新文件
}
printf("%d",count); //输出行数
fclose(rfp); //关闭文件
fclose(wfp);
return 0;
}
3> 向文件中每一秒打印当前系统时间
#include <myhead.h>
#include<time.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
int count = 0; //统计行数
time_t t_sec1; //标记时间,实现一秒输出一次
FILE* fp = fopen("123.txt","a");
//获取文件中的行数,实现下次此运行后不从零开始
FILE* rfp = fopen("123.txt","r");
while(1){
char ch = fgetc(rfp);
if(ch == '\n')count++;
if(ch==EOF)break;
}
while(1){
time_t t_sec = time(NULL);
struct tm *tm_t=localtime(&t_sec);
if(t_sec1!=t_sec){
//将时间输出到终端
printf("%2d %4d-%2d-%2d %2d:%2d:%2d\n",count,tm_t->tm_year+1900,tm_t->tm_mon+1,tm_t->tm_mday,tm_t->tm_hour,tm_t->tm_min,tm_t->tm_sec);
//将文件输出到文件
fprintf(fp,"%2d %4d-%2d-%2d %2d:%2d:%2d\n",count,tm_t->tm_year+1900,tm_t->tm_mon+1,tm_t->tm_mday,tm_t->tm_hour,tm_t->tm_min,tm_t->tm_sec);
//每输出一次行数加一
count++;
//手动刷新缓存区
fflush(fp);
}
//使标记时间等于最新的时间
t_sec1 = t_sec;
}
return 0;
}