Linux---文件操作
将1.txt中的数字读出来,再逆序输出到2.txt中去,要求逆序
熟悉 fopen fclose fprintf,fscanf的用法
#include<stdio.h>
#include<stdlib.h>
#define INCREASE 20
int main()
{ int max=10;
FILE*fp1;
FILE*fp2;
int *array=(int*)malloc(max*sizeof(int));
int *temp;
fp1=fopen("1.txt","r");
if(fp1==NULL)
{
printf("open 1.txt error\n");
exit(-1);
}
fp2=fopen("2.txt","w");
if(fp2==NULL)
{
printf("open 2.txt error\n");
exit(-1);
}
int i=0,j=0;
while(fscanf(fp1,"%d",&array[i])!=EOF)
{ i++;
if(i>=max)
{ max+=INCREASE;
temp=(int*)realloc(array,max*4);
if(temp==NULL)
{
printf("realloc error\n");
exit(-1);
}
array=temp;
}
}
j=i;
for(i=j-1;i>=0;i--)
{
fprintf(fp2,"%d\n",array[i]);
}
fclose(fp1);
fclose(fp2);
}
浙公网安备 33010602011771号