从文本文件中读取结构
问题描述:
我需要从文件中读取struct
,但我的代码不起作用。 我怎样才能达到文件从文本文件中读取结构
#include<stdio.h>
typedef struct elements {
char CallType;
int noofcparty,nooPartyBcalling,id,number_of_packets,roaming_option;
} Elements;
int main()
{
Elements e;
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("save_data.txt","r");
fclose(ptr_file);
getchar();
getchar();
return 0;
}
答
的端我假定该文件是在CSV(逗号分隔值)。例如:b,100,200,800,45。
char line[200];
int max_size_line=200;
while(fgets(line,max_size_line,ptr_file)!=0)//read line by line until the end
{ sscanf(line,"%c,%d,%d,%d,%d,%d",&CallType,&noofcparty,&nooPartyBcalling,&id,&number_of_packets,&roaming_option);
}
阅读关于['fgets'](http://en.cppreference.com/w/c/io/fgets)和['sscanf'](http://en.cppreference.com/w/C/IO /的fscanf)。 –
如果要存储和检索结构的二进制内存中表示形式,可以使用'fwrite'和'fread'。 –