我正在做一个项目,我必须读取 .txt 文件,其中我有每个组件的四个元素的数据,例如:5 2 7 0.99(这是组件 ID、内部节点、外部节点和可靠性)7 3 5 0.95 ...我想将数据读写到一个链表中,稍后我将能够在该链表上搜索值并将它们签名到一个新的链表中。它是关于机械工程中用于计算系统可靠性的最小路径方法。
为了测试代码,我只想打印出所有放入链表的组件。我得到了正确的行数值,但对于组件,我只是随机取出一个,而不是全部。任何形式的帮助将不胜感激:)
这是代码:
#include <stdlib.h>
#include <stdio.h>
struct Components_element {
int id;
int in_node;
int out_node;
float reliability;
struct Components_element *next_c;
};
struct Components_element *head_c = NULL;
int count_lines(char *filename)
{
int counter = 0;
char c;
FILE *ptr_sistem;
ptr_sistem = fopen(filename, "r");
if(ptr_sistem == NULL)
return 0;
while((c = fgetc(ptr_sistem)) != EOF)
if(c == '\n')
counter++;
fclose(ptr_sistem);
if(c != '\n')
counter++;
return counter;
}
struct Components_element *add_comp(struct Components_element *head_c, int id, int in_node, int out_node, float reliability)
{
struct Components_element *new;
struct Components_element *tail_c;
new = (struct Components_element*) malloc(sizeof(struct Components_element));
new->id = id;
new->in_node = in_node;
new->out_node = out_node;
new->reliability = reliability;
if(head_c == NULL)
return(new);
tail_c = head_c;
while(tail_c->next_c != NULL)
tail_c = tail_c->next_c;
tail_c->next_c = new;
return(head_c);
}
void write_out(struct Components_element *p)
{
while(p != NULL) {
printf("%d %d %d %f", p->id, p->in_node, p->out_node, p->reliability);
p = p->next_c;
}
printf("\n");
}
struct Components_element *empty(struct Components_element *p)
{
struct Components_element *tail_c;
while(p != NULL) {
tail_c = p;
p = p->next_c;
free(tail_c);
}
return(p);
}
main()
{
int i, id, in_node, out_node;
int n_lines;
float reliability;
struct Components_element *components;
FILE *ptr_file;
ptr_file = fopen("system.txt", "r");
if(ptr_file == NULL) {
printf("Cannot open file.\n");
return 0;
} else {
n_lines = count_lines("system.txt");
for(i = 0; i < n_lines; i++) {
fscanf(ptr_file, "%d %d %d %f", &id, &in_node, &out_node, &reliability);
components = add_comp(head_c, id, in_node, out_node, reliability);
++i;
}
}
printf("Number of lines: %d.\n", n_lines);
write_out(components);
empty(components);
fclose(ptr_file);
}