将结果从文件传递到另一个文件

时间:2018-05-02 07:02:40

标签: c file

问候语。一世 我创建了一个要求姓名和年龄的文件,我想提取输入到文件中的年龄数,并将该数字打印在其他文件中。 我知道我可以根据有多少名字,甚至是我要求提供信息的次数来计算,但我需要根据数字来计算我得到的年龄,在这种情况下 int ,并将其打印在其他文件上。 这是我的代码:

#define T 50
#define A 5
void main ()
{
   FILE *ap=NULL, *ap2=NULL;
   char cad[T];
   int age, x,cont=0;

   ap=fopen("Dat.txt", "w+"); //Open File
   if(ap==NULL)
   {  printf("Cant open the file");
      getch();
      exit(1);
   }
   ap2=fopen("Ages.txt","w"); //Open File
   if(ap2==NULL)
   {  printf("Cant open the file");
      getch();
      exit(1);
   }
   for(x=0;x<A;x++) //Gets the information
   {  printf("Name: ");
      gets(cad);
      printf("Age: ");
      scanf("%d",&age);
      fflush(stdin);
      fprintf(ap,"%-30s %d\n",cad,age);
   }
   rewind(ap);
   fgets(cad,T,ap);
   while(!feof(ap))     //Start counting the ages
   {  fscanf(ap,"%d",&age);
      ++cont;
   }
   fprintf(ap2,"%d", cont);

   fclose(ap); fclose(ap2); //Close both Files

它可以很好地创建文件&#34; Dat.txt&#34;如果我评论最后6行代码(除了 fclose ),所有信息,但它似乎进入循环,因为它在我输入信息时没有做任何事情。

1 个答案:

答案 0 :(得分:0)

问题出在fscanf(ap,"%d",&age);循环的while行。这是因为你写了一个字符串拳,你期望阅读int

将其替换为以下代码段,它将解决您的问题:

...
rewind(ap);
fgets(cad,T,ap);
while(!feof(ap))     //Start counting the ages
{
   //Move pointer to 30, Since while writing to file width is set to 30(%-30s) 
   age = atoi(cad+30); 
   printf("%d\n",age);
   ++cont;
   fgets(cad,T, ap);
}
fprintf(ap2,"%d", cont);
...