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

标签 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

如果我注释最后 6 行代码(除了 fclose),它可以很好地创建包含所有信息的文件“Dat.txt”,但它似乎进入了循环,因为它当我输入完信息后没有做任何事情。

最佳答案

问题出在 while 循环的 fscanf(ap,"%d",&age); 行中。这是因为您已经编写了一个字符串拳头,并且您期望读取一个 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);
...

关于c - 将结果从一个文件传递到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128840/

相关文章:

c - %c 在 GCC 内联汇编代码中是什么意思?

c - 计时器处于向上模式

java - 使用Tomcat和servlet时如何删除txt文件?

bash - 如何将一个文件逐行放入另一个文件中

java - 通过套接字发送大文件时出错

git - 如何从 Git 存储库中提取任何提交到文件夹/存档的所有文件?

java - 以编程方式将 txt 文件从 ANSI 转换为 UTF-8

python - 如何使用 pyhunspell 向 .dic/.aff 文件添加新词?

c - 打印标准输入中的每一行

无法在 Arduino 环境中定义 A8