c语言将数据结构写入到文件并读取
2013 年 7 月 10 日 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;
}
#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;
}
发表评论