C从文本文件

时间:2016-10-02 19:03:47

标签: c file struct

我有一个存储为文本的结构数组;每个数组项以一个数字开头,后跟一个结束括号,后面跟着一行中每个结构成员的数据。例如

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

你能帮我写一个循环,将每个循环读入一个结构数组

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");

1 个答案:

答案 0 :(得分:0)

我没有测试过这个,除了检查它编译,但它应该做的诀窍

#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;
}