简体   繁体   English

如何从文件读取到c中的结构

[英]how to read from a file in to a struct in c

I have this struct. 我有这个结构。

Struct Wizard{
 char name[50];
 int maxHealth;
 int attackMin, attackRange;
 int curHealth, winCount;
};

And I need to make a function save the stats to a txt file. 我需要使函数将统计信息保存到txt文件中。
I was given this bit of code to start it. 我得到了这段代码来启动它。

int saveWiz(struct Wizard * wiz)
{
  File * fp = fopen("champion.txt","w");
  char * buff = malloc(100);
  sprintf(buff,... );
  sprintf(buff,...);
  //Todo: replace ... with appropriate string, using tags like %d for variables
  fputs(buff,fp);
  fclose(fp);
}

Any help would be much appreciated. 任何帮助将非常感激。 I think I am supposed to use the wiz pointer to access the struct but I'm not exactly sure. 我想我应该使用wiz指针来访问结构但我不确定。

I don't know if I understand exactly what you are asking but I'm guessing it's this: 我不知道我是否完全理解你在问什么,但我猜它是这样的:

You have a wiz variable of type struct Wizard * . 你有一个struct Wizard *类型的wiz变量。 You access the elements like this : wiz->name , wiz->maxHealth and so on, wiz->name is equivalent to (*wiz).name . 您可以访问以下元素:wiz-> name,wiz-> maxHealth等,wiz-> name等同于(* wiz).name。 So you'll have : 所以你会有:

int saveWiz(struct Wizard * wiz)  //assuming you return 1 for success 0 for failure
{
  File * fp = fopen("champion.txt","w");
  if(!fp) {
    //file opening failed
   return 0;
}
  char * buff = malloc(200); // 200 to be sure
  if(buff) {
  sprintf(buff,"%s",wiz->name);
  sprintf(buff,"%d %d %d %d %d" , wiz->maxHealth,  wiz->attackMin,    wiz->attackRange, wiz->curHealth, wiz->winCount);
  fputs(buff,fp);
  fclose(fp);
  free(buff);
  return 1;
  }
else {
   //memory allocation failed
return 0;
}

}

Also as Martin James pointed out it is best to free dynamically allocated memory after you're done using it ( otherwise causes ugly memory leaks on long-running programs) . 同样,正如Martin James指出的那样,最好在使用完动态分配的内存后释放它(否则会导致长时间运行的程序出现难看的内存泄漏)。 On that note , it's also good to check if the file opening was successful as well as the memory allocation. 在这方面,检查文件打开是否成功以及内存分配也是很好的。 Also another thing I noticed is the number of elements in the buff array , 100 might not be enough ( considering an int is 32 bit (10 digits) and the name has a full 50 characters, along with the spaces it might cause an overflow). 另外我注意到的另一件事是buff数组中的元素数量,100可能不够(考虑到int是32位(10位)并且名称有完整的50个字符,以及它可能导致溢出的空格) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM