0

私は、各コンポーネントの 4 つの要素のデータがある .txt ファイルを読み取る必要があるプロジェクトに取り組んでいます。例: 5 2 7 0.99 (コンポーネント ID、ノード内、ノード外、および信頼性) 7 3 5 0.95 ... リンクされたリストにデータを読み書きしたいのですが、後で値を検索して新しいリンクされたリストに署名することができます。これは、システムの信頼性を計算するために使用される機械工学の最小パスの方法に関するものです。

コードをテストするには、リンクされたリストに配置されたすべてのコンポーネントを出力したいだけです。行数の正しい値を取得しますが、コンポーネントの場合、すべてではなくランダムに1つ取得します。どんな種類の助けも大歓迎です:)

コードは次のとおりです。

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

1 に答える 1