我应该读取一个 C 语言的文件,其结构如下所示
A:
1
2
3
4
B:
1 1
2 2
3 3
4 4
C:
1 1 1
2 2 2
3 3 3
4 4 4
文件始终分为三个部分,每个部分都以标识符开头(A:、B:、..)。 标识符后跟包含数据的未指定数量的行。但每个部分的数据格式都不同。而且它不仅仅是整数,但这在这个问题中并不重要。
我在读取文件时没有遇到问题。我的问题是读取此类文件的最佳方法是什么?它可以包含数千行甚至更多的部分,而不仅仅是三个。例如,结果应该是字符串数组,每个数组包含来自文件不同部分的行。
我没有发布任何代码,因为我也不需要/不希望你发布任何代码。这个想法对我来说已经足够好了。
最佳答案
您可以逐行读取文件并每次检查是否有新部分开始。如果是这种情况,请为新节分配新内存,并将以下所有行读取到该新节的数据结构中。
对于动态内存分配,您将需要一些计数器,以便您知道每个部分有多少行以及您总共阅读了多少部分。
为了说明这个想法(没有完整的代码):
typedef struct {
int count;
char **lines;
} tSection;
int section_counter = 0;
tSection *sections = NULL;
tSection *current_section = NULL;
char line[MAXLINE];
while (fgets(line, MAXLINE, file)) {
if (isalpha(line[0])) { // if line is identifier, start new section
sections = realloc(sections, sizeof(tSection)*(section_counter+1));
current_section = §ions[section_counter];
current_section->lines = NULL;
current_section->count = 0;
section_counter++;
}
else { // if line contains data, add new line to structure of current section
current_section->lines = realloc(current_section->lines, sizeof(char*)*(current_section->count+1));
current_section->lines[current_section->count] = malloc(sizeof(char)*MAXLINE);
strcpy(current_section->lines[current_section->count], line);
current_section->count++;
}
}
关于c - 读取包含多种数据格式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58516636/