gpt4 book ai didi

C从文本文件中读取结构

转载 作者:行者123 更新时间:2023-11-30 19:37:27 25 4
gpt4 key购买 nike

我有一个存储为文本的结构数组;每个数组项都以数字开头,后跟一个右括号,然后是每个结构成员的数据(单独一行)。例如

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

最佳答案

除了检查它的编译情况之外,我还没有对此进行测试,但它应该可以解决问题

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

关于C从文本文件中读取结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com