C структура fwrite () в файл - PullRequest
0 голосов
/ 11 июля 2020

Приветствую,

Noob в C ищет помощь, касающуюся fwrite() a c структуры файла .txt.

После выполнения я получаю .txt файл, содержащий некоторые символы руби sh вместо моей структуры. (Z� <�U���; �U3�y`T����; �U�v �?��; �U�y) </p>

Вот мой простой код:

#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;
}

1 Ответ

1 голос
/ 11 июля 2020

действительно, я испортил неправильные параметры для fopen (), поэтому, как сказано здесь, вместо:

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

должно быть:

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

Также попробую преобразовать строку решение, чтобы проверить разницу.

Всем спасибо.

...