c - 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;
}
解决方案
确实我把错误的参数给 fopen() 搞砸了,所以在这里告诉而不是:
fwrite(&Motorcycles[4],sizeof(struct Motorcycle),1,file_open);
一定是:
fwrite(Motorcycles,sizeof(struct Motorcycle),4,file_open);
还将尝试字符串转换解决方案来检查差异。
感谢大家。
推荐阅读
- linux - 当我升级archlinux时,存在依赖问题。我该如何解决?
- python - matplotlib - 将 xtick 标签值替换为其他标签值的日志格式
- ibm-cloud - 适用于 Cloudant 的 IBM Watson IoT 平台历史数据连接器
- javascript - 我尝试要求 nodejs fs 模块并不断收到以下错误,请问我该怎么做?
- java - 布尔值不能转换为字符串
- c++ - Clion 编辑器无法识别标准 C++ 库
- node.js - 如何在 MongoDB 中按各种标准高效查找文档?
- python - 如何将 curl 调用转换为 python 请求调用
- html - 是否可以将
块下方 堵塞? - r - R studio中根据不同城市名称的条件求和