1、fgetc和fputc拷贝文件。
#include <myhead.h>
int main(int argc, const char *argv[])
{
/*
*/
if(argc != 3)
{
printf("外部参数错误\n");
return -1;
}
FILE *fp1 = fopen("./1.txt","r");
if(NULL == fp1)
{
perror("fp1");
return -1;
}
FILE *fp2 = fopen("./2.txt","w");
if(NULL == fp2)
{
perror("fp2");
return -1;
}
char buff;
while((buff = fgetc(fp1)) != EOF)
{
fputc(buff,fp2);
}
fclose(fp1);
fclose(fp2);
printf("拷贝成功\n");
fp2 = fopen("./2.txt","r");
if(NULL == fp2)
{
perror("fp2");
return -1;
}
while(1)
{
char rev = fgetc(fp2);
if(rev == EOF)
{
break;
}
fputc(rev,stdout);
}
fclose(fp2);
return 0;
}
2、fgets获取文件的行号。
#include <myhead.h>
int main(int argc, const char *argv[])
{
/*
*/
FILE *fp;
fp = fopen("./1.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
char buff[100];
int m = 0,i = 0;
while(fgets(buff,sizeof(buff),fp) != NULL)
{
for(i = 0;buff[i] != 0;i++)
{
if(buff[i] == 10)
{
m++;
}
}
}
printf("%d",m);
putchar(10);
fclose(fp);
return 0;
}
3、fgets和fputs拷贝文件。
#include <myhead.h>
int main(int argc, const char *argv[])
{
/*
*/
if(argc != 3)
{
printf("外部参数错误\n");
return -1;
}
FILE *fp1 = fopen("./1.txt","r");
if(NULL == fp1)
{
perror("fp1");
return -1;
}
FILE *fp2 = fopen("./2.txt","w");
if(NULL == fp2)
{
perror("fp2");
return -1;
}
char buff[100];
while(fgets(buff,sizeof(buff),fp1) != NULL)
{
fputs(buff,fp2);
}
fclose(fp1);
fclose(fp2);
printf("拷贝成功\n");
fp2 = fopen("./2.txt","r");
if(NULL == fp2)
{
perror("fp2");
return -1;
}
while(1)
{
char rev[100];
if(fgets(rev,sizeof(rev),fp2) == NULL)
{
break;
}
printf("%s",rev);
}
fclose(fp2);
return 0;
}