【问题标题】:C fwrite() structure to fileC fwrite() 结构到文件
【发布时间】:2020-11-01 03:12:42
【问题描述】:

您好,

C 中的菜鸟正在寻找一些关于 fwrite() .txt 文件的 c 结构的帮助。

执行后,我得到一个包含一些 rubish 符号而不是我的结构的 .txt 文件。 (Z�

这是我的简单代码:

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

【问题讨论】:

  • 你应该首先检查fopen("motorcycles.txt","w")是否失败。
  • fwrite 只是在写入结构的原始字节。如果您希望它们是人类可读的,那么您需要将它们转换为字符串。最简单的方法是使用fprintf
  • Motorcycles[4] 不存在。你写不出来。请记住,C 中的索引来自 0..n-1
  • fopen("motorcycles.txt","w");销毁文件的现有内容。
  • 您还尝试打印出 6 个结构的内容,而您只分配了 4 个。这里发生了一些未定义的行为。

标签: c file gcc structure fwrite


【解决方案1】:

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

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

必须是:

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

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

谢谢大家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多