c - 从链接列表保存到文件并将其加载回来

标签 c file linked-list

我在从文件加载到链接列表时遇到问题,一整天都在尝试

首先这是我的结构

typedef struct Sensor {
    int id;
    int intervalo;
    char local[30];
    char tipo[30];
    //bool active;
    int active;
    struct Sensor* anterior;
    struct Sensor* proximo;
} Sensor;

这是我的保存功能,我认为它工作正常,因为文件已创建并且内容就在那里。

void gravaLista(Sensor* l) {
    FILE *ficheiro;
    Sensor* temp = l;
    ficheiro = fopen("sensores.txt", "r+t");

    if (ficheiro == NULL) {
        ficheiro = fopen("sensores.txt", "w+t");
    }

    while (temp != NULL) {
        fprintf(ficheiro, "%d%d%d%30s%30s", temp->id, temp->intervalo, temp->active,
        temp->local, temp->tipo);
        temp = temp->proximo;
    }

    fclose(ficheiro);
}

现在,无论我读到什么,我似乎都无法使其工作,那就是加载函数。

这是我的自动取款机

int CarregaTodos(Sensor** l) {
    Sensor sens;
    FILE *ficheiro;
    int i = 0;

    ficheiro = fopen("sensores.txt", "r+t");

    if (ficheiro == NULL) {
        printf("no file\n", "sensores.txt");
        return i;
    }

    rewind(ficheiro);
    while (fscanf(ficheiro, "%d%d%d%30s%30s", &sens.id, &sens.intervalo, &sens.active,
            &sens.local, &sens.tipo) == 5) {

            //novo() function returns a pointer to a new element and insereSensor adds the new element to the last position of the list
            insereSensorFim(&l, novo(sens.id, sens.intervalo, sens.local, sens.tipo));                              //this function inserts the new element at the end of the list
    }

    fclose(ficheiro);
    return i;
}

辅助函数在加载函数之外工作正常,但是当我在加载后尝试打印列表时,没有任何内容被打印。我错过了什么?

编辑:我也只发布辅助函数

Sensor* novo(int id, int tempo, char* l, char* t) {

    Sensor* novoSensor = (Sensor*)malloc(sizeof(struct Sensor));

    //novoSensor->id = ++(*totalSens);
    novoSensor->id = id;
    novoSensor->intervalo = tempo;
    strcpy(novoSensor->local, l);
    strcpy(novoSensor->tipo, t);
    novoSensor->active = 1;
    novoSensor->anterior = NULL;
    novoSensor->proximo = NULL;

    //gravaSensor(novoSensor, (*totalSens), 1);

    return novoSensor;
}

void insereSensorFim(Sensor** Lista, Sensor* novo) {

    Sensor* atual = *Lista;

    if ((*Lista == NULL))
        (*Lista = novo);

    else {

        while (atual->proximo != NULL) {
            atual = atual->proximo;
        }

        atual->proximo = novo;
        novo->anterior = atual;
    }
}

edit2:现已修复,感谢所有发表评论的人,您可以阅读所有评论或仅阅读https://stackoverflow.com/a/44078897/8038340

最佳答案

正确使用 printf()scanf() 非常困难。可以用它们施展各种魔法,但您需要知道它们是如何工作的才能施展这种魔法。

在示例代码中,由于在输出中不包含记录分隔符,您的生活变得更加困难。换行符是传统且最简单的分隔符,但您可以根据需要选择其他分隔符,或者不选择分隔符。但是,如果您选择不选择分隔符,则您必须了解问题中未给出的数据的信息。如果字符串从不包含空格,则您的格式可以不那么严格。但是您必须有某种方法知道一个数字在哪里结束以及下一个数字在哪里开始 - 您不能像示例 printf() 格式那样简单地将所有数字混合在一起,除非它们都是负数,或者在正数后添加一个加号 (%+d)。必须有某种方法来告诉 scanf() 何时停止读取一个数字并开始读取下一个数字。

这段代码是我在大量评论中所写内容的详细阐述。输出格式使用固定宽度字段;这使得阅读它们变得更容易。它不假设字符串中没有空格,因此它使用 %29c 读取 29 个字符,并添加空终止符并通过 strip_blanks() 删除尾随空格。它包括打印列表的代码;它使用该代码。

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Sensor
{
    int id;
    int intervalo;
    char local[30];
    char tipo[30];
    int active;
    struct Sensor *anterior;
    struct Sensor *proximo;
} Sensor;

static void insereSensorFim(Sensor **Lista, Sensor *novo);
static Sensor *novoSensor(int id, int tempo, char *l, char *t);

static const char *outfile = "sensores.txt";

static
void gravaLista(Sensor *l)
{
    FILE *ficheiro = fopen(outfile, "w");
    if (ficheiro == NULL)
    {
        fprintf(stderr, "Failed to open file '%s' for writing\n", outfile);
        exit(1);
    }

    Sensor *temp = l;
    while (temp != NULL)
    {
        fprintf(ficheiro, "%11d%11d%11d%-29.29s%-29.29s", temp->id, temp->intervalo, temp->active,
                temp->local, temp->tipo);
        temp = temp->proximo;
    }

    fclose(ficheiro);
}

/* Strip trailing blanks and null terminate string */
static inline void strip_blanks(char *data, size_t size)
{
    assert(size > 0);
    size_t offset = size - 1;
    data[offset--] = '\0';
    while (offset > 0 && data[offset] == ' ')
        data[offset--] = '\0';
}

static
int CarregaTodos(Sensor **l)
{
    Sensor sens;
    FILE *ficheiro;
    int i = 0;

    ficheiro = fopen(outfile, "rt");

    if (ficheiro == NULL)
    {
        fprintf(stderr, "Failed to open file '%s'\n", outfile);
        exit(1);
    }

    while (fscanf(ficheiro, "%11d%11d%11d%29c%29c", &sens.id, &sens.intervalo, &sens.active,
                  sens.local, sens.tipo) == 5)
    {
        strip_blanks(sens.local, sizeof(sens.local));
        strip_blanks(sens.tipo, sizeof(sens.tipo));
        insereSensorFim(l, novoSensor(sens.id, sens.intervalo, sens.local, sens.tipo));
    }

    fclose(ficheiro);
    return i;
}

static inline void str_copy(char *dst, const char *src, size_t size)
{
    assert(size > 0);
    strncpy(dst, src, size - 1);
    dst[size - 1] = '\0';
}

static
Sensor *novoSensor(int id, int tempo, char *l, char *t)
{
    Sensor *novoSensor = (Sensor *)malloc(sizeof(struct Sensor));
    if (novoSensor == NULL)
    {
        fprintf(stderr, "Failed to allocate %zu bytes memory\n", sizeof(struct Sensor));
        exit(1);
    }

    novoSensor->id = id;
    novoSensor->intervalo = tempo;
    str_copy(novoSensor->local, l, sizeof(novoSensor->local));
    str_copy(novoSensor->tipo, t, sizeof(novoSensor->tipo));
    novoSensor->active = 1;
    novoSensor->anterior = NULL;
    novoSensor->proximo = NULL;

    return novoSensor;
}

static
void insereSensorFim(Sensor **Lista, Sensor *novo)
{
    Sensor *atual = *Lista;

    if ((*Lista == NULL))
        *Lista = novo;
    else
    {
        while (atual->proximo != NULL)
            atual = atual->proximo;
        atual->proximo = novo;
        novo->anterior = atual;
    }
}

static void print_sensor(Sensor *sensor)
{
    printf("%5d %5d %1d [%-29s] [%-29s]\n", sensor->id, sensor->intervalo,
           sensor->active, sensor->local, sensor->tipo);
}

static void print_sensor_list(const char *tag, Sensor *list)
{
    printf("%s:\n", tag);
    while (list != 0)
    {
        print_sensor(list);
        list = list->proximo;
    }
}

static void free_sensor_list(Sensor *list)
{
    while (list != 0)
    {
        Sensor *next = list->proximo;
        free(list);
        list = next;
    }
}

int main(void)
{
    Sensor *list = 0;

    print_sensor_list("Empty", list);

    insereSensorFim(&list, novoSensor(10231, 23, "abc123-bothersome",  "d92-x41-ccj-92436x"));
    insereSensorFim(&list, novoSensor(20920, 25, "def456-troublesome", "e81-p42-ggk-81366x"));
    insereSensorFim(&list, novoSensor(30476, 83, "ghi789-wearisome",   "f70-q43-omm-70296x"));

    print_sensor_list("After insertion", list);
    gravaLista(list);
    free_sensor_list(list);
    list = 0;
    print_sensor_list("Emptied", list);

    CarregaTodos(&list);
    print_sensor_list("After rereading", list);

    insereSensorFim(&list, novoSensor(231,  325, "jkl012 blank laden stream",       "minimum mess or cleaning"));
    insereSensorFim(&list, novoSensor(6812, -11, "mno345 longer than was expected", "maximum type of untidiness at work"));
    print_sensor_list("After extending", list);

    free_sensor_list(list);

    return 0;
}

运行时,它会产生输出:

Empty:
After insertion:
10231    23 1 [abc123-bothersome            ] [d92-x41-ccj-92436x           ]
20920    25 1 [def456-troublesome           ] [e81-p42-ggk-81366x           ]
30476    83 1 [ghi789-wearisome             ] [f70-q43-omm-70296x           ]
Emptied:
After rereading:
10231    23 1 [abc123-bothersome            ] [d92-x41-ccj-92436x           ]
20920    25 1 [def456-troublesome           ] [e81-p42-ggk-81366x           ]
30476    83 1 [ghi789-wearisome             ] [f70-q43-omm-70296x           ]
After extending:
10231    23 1 [abc123-bothersome            ] [d92-x41-ccj-92436x           ]
20920    25 1 [def456-troublesome           ] [e81-p42-ggk-81366x           ]
30476    83 1 [ghi789-wearisome             ] [f70-q43-omm-70296x           ]
  231   325 1 [jkl012 blank laden stream    ] [minimum mess or cleaning     ]
 6812   -11 1 [mno345 longer than was expect] [maximum type of untidiness at]

输出文件sensores.txt如下所示:

      10231         23          1abc123-bothersome            d92-x41-ccj-92436x                 20920         25          1def456-troublesome           e81-p42-ggk-81366x                 30476         83          1ghi789-wearisome             f70-q43-omm-70296x           

分割成记录时,即:

      10231         23          1abc123-bothersome            d92-x41-ccj-92436x           
      20920         25          1def456-troublesome           e81-p42-ggk-81366x           
      30476         83          1ghi789-wearisome             f70-q43-omm-70296x           

11 的整数宽度允许前两列中的每一列中存在负 32 位数字。如果您知道数字较小,则可以减少使用的空间。在 scanf() 中,您可以省略整数字段的长度;它的工作原理是相同的,因为数字格式会自动跳过空格。 printf() 可以添加换行符;扫描代码根本不需要更改,因为 scanf() 在需要数字(或字符串 - 仅 %c)时不关心换行符,%[…] 扫描集,并且 %n 不跳过前导空格)。

您还可以安排一些不会出现在字符串中的字符(可能是 Control-A、'\1')来分隔字符串。然后扫描代码可以查找它,并且您可以得到可变长度的输出。

留给我自己的设备,我可能会使用带有换行符的可变长度记录作为记录分隔符,为两个字符串使用合适的字段分隔符,以及不太严格的 scanf()格式。我会用 fgets() 或 POSIX 读取这些行 getline() 然后使用扫描行 sscanf() 。除非您的字符串中可以有换行符,否则这会很好地工作。

正如我最近在另一个 answer 中所说的那样 — 稍微解释一下:

Read the POSIX specification of printf() and scanf() for the full details. They do have some (clearly marked) extensions over standard C printf() and scanf(), but they serve for both POSIX and standard C. Then re-read them. And re-re-read them. And do that daily for a week, and then weekly for a month, and then monthly for a year, and then yearly ever after. It will repay the effort.

关于c - 从链接列表保存到文件并将其加载回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44077339/

相关文章:

c - 求 C 语言中最大的数字,但带有字符

代码可以运行,但有一些小错误,我不知道它在哪里?

c++ - "bit padding"或 "padding bits"到底是什么?

c - 如何将值传递给结构变量然后将结构写入文件?

只能通过这个循环这么多次迭代吗?

C程序在链表中按升序添加和删除节点

c - 在链表计算器中添加值

c - 对数字数组求和但在运行时收到错误

java - 如何读取包含文本和图像数据的文件?

python - 比较两个文件报告python中的差异