简体   繁体   English

C从文本文件中读取结构

[英]C reading struct from text file

I have an array of structures stored as text;我有一个存储为文本的结构数组; each array item begins with a number followed by a closing bracket, followed by the data for each struct member on a line on its own.每个数组项以一个数字开头,后跟一个右括号,后跟每个结构成员的数据单独一行。 For example例如

1)
Andrew
Bilous
Andriyovuch
director
1
1000
2)
... and so on...

Can you help me to write a loop that will read each one into a single array of structures你能帮我写一个循环,将每个循环读入一个结构数组吗

struct spivrob {
    char *name;
    char *surname;
    char *pobat;
    char *posada;
    int staz;
    int oklad;
} tab[6];
FILE *fo;
fo = fopen("C:\\Users\\andyb\\Desktop\\test7.txt","r");

I've not tested this, other than to check it compiles, but it should do the trick我没有测试过这个,除了检查它编译之外,但它应该可以解决问题

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

char* initAndGetNextLine(FILE* fo, size_t length);
int getNextLineLength(FILE* fo);

int main()
{
   struct spivrob {
      char *name;
      char *surname;
      char *pobat;
      char *posada;
      int staz;
      int oklad;
   } tab[6];

   FILE *fo = fopen("C:\\Users\\andyb\\Desktop\\test7.txt","r");

   char*  line   = NULL;
   size_t length = 0;
   int    i      = 0;
   int    j      = -1;

   while(!feof(fo) && !ferror(fo))  {
      int len         = getNextLineLength(fo);
      char* newString = (i %7 < 5)? initAndGetNextLine(fo, len) : NULL;
      switch(i % 7) {
        case 0: j++;
        case 1: tab[j].name = newString; break;
        case 2: tab[j].surname = newString; break;
        case 3: tab[j].pobat = newString; break;
        case 4: tab[j].posada = newString; break;
        case 5: tab[j].staz = atoi(line); break;
        case 6: tab[j].oklad = atoi(line); break;
      }
      i++;
   } 
}

int getNextLineLength(FILE* fo)
{
   char c;
   int i = 0; 
   do {
      c = fgetc(fo);
      i++;
   } while(c != '\n' && !feof(fo) && !ferror(fo));
   fseek(fo, -i, SEEK_CUR);
   return i; 
}

char* initAndGetNextLine(FILE* fo, size_t length) 
{
   char* newString = malloc(length * sizeof(char) + 1);
   fgets(newString, length, fo);
   newString[length] = '\0';
   return newString;
}

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

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