1
#include <head.h>
int main(int argc, char const *argv[])
{
FILE *fp=NULL;
fp=fopen("./text.txt","w");
fputs("Hello world\n", fp);
fputs("I love China\n", fp);
fputs("Hua qing yuan jian\n", fp);
fputs("good good study day day up\n", fp);
fclose(fp);
if((fp = fopen("./text.txt", "r")) == NULL)
{
perror("fopen error");
return -1;
}
char buf[128] = "";
int sum=0;
while(1)
{
bzero(buf, sizeof(buf));
if( fgets(buf, sizeof(buf), fp) == NULL)
{
break;
}
if(buf[strlen(buf)-1]=='\n')
sum++;
printf("%s",buf);
}
printf("给定文件共%d行\n",sum);
fclose(fp);
return 0;
}
2
#include <head.h>
int main(int argc, char const *argv[])
{
FILE *fp=NULL;
FILE*fq=NULL;
fp=fopen("./text.txt","w");
fputs("Hello world\n", fp);
fputs("I love China\n", fp);
fputs("Hua qing yuan jian\n", fp);
fputs("good good study day day up\n", fp);
fclose(fp);
fq=fopen("./dest.txt","w");
if((fp = fopen("./text.txt", "r")) == NULL)
{
perror("fopen error");
return -1;
}
char buf[128]="";
while(1)
{
bzero(buf, sizeof(buf));
if( fgets(buf, sizeof(buf), fp) == NULL)
{
break;
}
fputs(buf,fq);
}
fclose(fq);
fclose(fp);
return 0;
}