在文件中保存C结构的问题!

问题描述

| 我试图将我的结构保存在file.txt中。我发现以下代码可以保存,但是问题是我希望每个ѭ0都保存在文件的另一行中!我无法修改代码
void WriteFile(struct car* q )
{
    printf(\"Attempting to write...\");
   FILE* fp = 0;
   char* buffer = 0;
   int i=0;

   /* allocate */
   buffer = malloc ( 150 );
   bzero( buffer,150 );

   /* copy the data to a string */

   snprintf( buffer,150,\"%s\\t%s\\t%d\\t%s\\t%.2f\\t%.2f\\t%d/%d/%d\\t%d/%d/%d\\t%d/%d/%d\\n\",q->name,q->numberplate,q->km,q->phonenumber,q->overall_cost,q->paid_cost,q->dateIn->day,q->dateIn->month,q->dateIn->year,q->dateServiced->day,q->dateServiced->month,q->dateServiced->year,q->dateOut->day,q->dateOut->month,q->dateOut->year); 
   printf(\"\\n\"); 

   fp = fopen(\"arxeio3.txt\",\"a\" );
   fputs( buffer,fp );
   fputs(\"\\n\",fp);

   free( buffer );
   fclose( fp );
}
    

解决方法

        此代码首先使用snprintf()将所有数据放入字符串中,然后将该字符串转储到文件中。因此,要更改输出的定界符,您必须更改传递给snprintf()的格式字符串。请注意,当前字段是如何用制表符(\\ t)或/分隔的。那些必须换行。 如果您使用的是Windows,则也请尝试使用\“ \\ r \\ n \”。     ,        您是否忘了循环浏览您的汽车收藏?您是否像这样将汽车驶过
WriteFile
struct car[MAX_CAR];
int numberOfCar=0;

... // code to fill in car and update numberOfCar

for(i=0;i<numberOfCar;++i)
  WriteFile(&car[i]);
您的
WriteFile
实现没有任何问题,只是缓冲区长度
150
可能不够     ,        您很有可能正在使用更喜欢\\ r \\ n而不是换行符(\\ n)的编辑器查看结果。尝试在NL之前添加\\ r(CR)。