我正在一个项目中,我必须读取.txt文件,其中每个组件包含四个元素的数据,例如:
5 2 7 0.99(它们是组件标识,内部节点,外部节点和可靠性)
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);
}

最佳答案

编写代码只是编程的一小部分。真正困难的部分是使它按要求工作。

为此,我们使用各种工具来辅助测试代码,以确保其按程序员预期的方式工作。

最有用的工具是调试器。了解如何使用它,您可以在几分钟内找到问题。

但是,有时调试器并不总是可用,这会使事情变得很棘手,并且需要记录信息(printf / fwrite /等)和许多演绎推理。

但是在这里,通过调试器运行代码将向您展示您的问题。我会把它留给您练习,因为您将通过这种方式学到更多东西,而不是把答案汤匙喂给您。

关于c - 将包含数据的文本文件读入链接列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16732372/

10-11 01:33
查看更多