首页 > 解决方案 > C fwrite() 结构到文件

问题描述

问候,

C 中的 Noob 正在寻找有关fwrite().txt 文件的 ac 结构的一些帮助。

执行后,我得到一个包含一些 rubish 符号而不是我的结构的 .txt 文件。(Z�<�U���;�U3�y`T����;�U�v���;�U�y)

这是我的简单代码:

#include <stdio.h>
#include <stdbool.h>

struct Motorcycle
{
 char company[20];
 char model_name[20];
 char engine_type[40];
 int engine_volume;
 int price;
 bool available;
};

int main()
{
struct Motorcycle Motorcycles[4]=
        {
         {"Harley Davidson","IRON 883","V-Twin: air-cooled",883,10765,true},
         {"Harley Davidson","STREED 750","V-Twin: water-cooled",750,7690,true},
         {"Harley Davidson","FORTY-EIGHT","V-Twin: air cooled evolution",1200,12590,true},
         {"Yamaha","XSR900","in-lined 3-cylinder engine",900,9999,true}
        };

int i;
for(i=0; i<4; i++)
{
 printf("\n Motocyrcle company: %s",Motorcycles[i].company);
 printf("\n Motorcycle model: %s",Motorcycles[i].model_name);
 printf("\n Motorcycle engine type: %s",Motorcycles[i].engine_type);
 printf("\n Motorcycle engien volume: %d",Motorcycles[i].engine_volume);
 printf("\n Motorcycle price: %d",Motorcycles[i].price);
 printf("\n Motorcycle available: %b",Motorcycles[i].available);
}

char user_input;
printf("Would you like to save it to file?\n");
scanf("%c",&user_input);

FILE *file_open;

if(user_input == 'y')
{
 file_open = fopen("motorcycles.txt","w");
 fwrite(&Motorcycles[4],sizeof(struct Motorcycle),1,file_open); fclose(file_open);
 printf("bikes copied");
 fclose(file_open);
}
 else
 {
  printf("Goodbye!");
  fclose(file_open);
 }



return 0;
}

标签: cfilegccstructurefwrite

解决方案


确实我把错误的参数给 fopen() 搞砸了,所以在这里告诉而不是:

fwrite(&Motorcycles[4],sizeof(struct Motorcycle),1,file_open);

一定是:

fwrite(Motorcycles,sizeof(struct Motorcycle),4,file_open);

还将尝试字符串转换解决方案来检查差异。

感谢大家。


推荐阅读