主页 > 未分类 > c语言将数据结构写入到文件并读取

c语言将数据结构写入到文件并读取

如下代码所示:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

// your struct
struct Data
{
    int first;
    double second;
    char third[10];
};

Data struct_read(){
  struct Data data;
 FILE* input;
 
  input = fopen("Data.dat", "rb");
 
  fread(&data, sizeof(data), 1, input);
 
  // you got the data from the file!
 
  fclose(input);
  return data;
}
void struct_write(){
 struct Data data = {22, 4.0, "Hi"};
 FILE* output;
 
  output = fopen("Data.dat", "wb");
 
  fwrite(&data, sizeof(data), 1, output);
 
  fclose(output);
}

int main(int argc, char *argv[]) {
 struct_write();
 Data data;
  data = struct_read();
 printf("%d, %f, %s",data.first, data.second,data.third);
 
  return 0;
}

发表评论

邮箱地址不会被公开。 必填项已用*标注