我正在编写一个 C 代码,它写入一些信号采样信息,然后读取它们并将它们存储到二进制文件中。当我写入信息时,我得到了正确的输出,但在尝试读取它们时出现了错误。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned int sample_offset;
double time;
unsigned int date;
unsigned char receiver_name[20];
double sample_rate;
unsigned int channel;
unsigned int bits;
unsigned char file_type[11];
unsigned int freq_band;
double channlel_bandwidth;
double firmwire_version;
double header_version;
} sampleInfo;
int main() {
// Writing file
FILE *fw;
sampleInfo data = { 64, 0.55, 19, "Gadfly", 51.2, 2, 4, "Spreadsheet", 1,24, 1.0, 1.0 }, read_data;
fw = fopen("sample.bin", "wb");
if (!fw) {
printf("Unable to open the file\n");
return 1;
} else {
printf("Sample offset: %d bytes\n", data.sample_offset);
printf("Capture time: %.2f seconds\n", data.time);
printf("Date: %d October,2018\n", data.date);
printf("Receiver name: %s\n", data.receiver_name);
printf("Sample rate: %.2f Mega-samples per second\n", data.sample_rate);
printf("Number of channels used: %d\n", data.channel);
printf("Number of bits per I and Q sample: %d\n", data.bits);
printf("File type: %s\n", data.file_type);
printf("Frequency band per channel: L%d\n", data.freq_band);
printf("Channel Bandwidth: %.fMHz\n", data.channlel_bandwidth);
printf("Firm-wire version: %.1f\n", data.firmwire_version);
printf("Header version: %.1f\n\n\n\n", data.header_version);
}
fwrite(&data, sizeof(sampleInfo), 1, fw);
fclose(fw);
// Reading file
FILE *fr;
fr = fopen("Sample.bin", "rb");
if (!fr) {
printf("Unable to open the file\n");
return 1;
} else {
printf("Sample offset: %d bytes\n", read_data.sample_offset);
printf("Capture time: %.2f seconds\n", read_data.time);
printf("Date: %d October,2018\n", read_data.date);
printf("Receiver name: %s\n", read_data.receiver_name);
printf("Sample rate: %.2f Mega-samples per second\n", read_data.sample_rate);
printf("Number of channels used: %d\n", read_data.channel);
printf("Number of bits per I and Q sample: %d\n", read_data.bits);
printf("File type: %s\n", read_data.file_type);
printf("Frequency band per channel: L%d\n", read_data.freq_band);
printf("Channel Bandwidth: %.fMHz\n", read_data.channlel_bandwidth);
printf("Firm-wire version: %.1f\n", read_data.firmwire_version);
printf("Header version: %.1f\n\n\n\n", read_data.header_version);
}
fread(&read_data, sizeof(sampleInfo), 1, fw);
fclose(fr);
return 0;
}
我对 C 语言比较陌生,所以对此有点挣扎。任何形式的帮助将不胜感激。提前致谢。
最佳答案
打印前请先阅读!
在打印文本之前,fread(&read_data,sizeof(sampleInfo),1, fr);
必须位于 else
分支中。
关于c - 用 C 编写和读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946947/