【问题标题】:Writing data from a linked list to a txt file in C将数据从链表写入 C 中的 txt 文件
【发布时间】:2016-11-14 15:57:21
【问题描述】:

我创建了这个程序,它首先询问您拥有多少只宠物,然后将每只宠物的姓名和年龄存储在一个结构中(全部使用链表)。

我的问题是:我正在尝试使用过程writeToFile() 将数据写入 .txt 文件,但在执行时,.txt 文件不包含任何数据。我不明白为什么?

这是我的代码:

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

struct Node {
    char *name;
    int age;
    struct Node *next;
};

struct Node * petRecord;
struct Node * newRecord;

void printPetRecord()
{  
    while(petRecord != NULL)
    {
        printf("Name of Pet: %s\n", petRecord->name);
        printf("Age of Pet: %d\n", petRecord->age);
        petRecord = petRecord->next;
    }
}

void writeToFile()
{
    FILE * fptr;
    fptr = fopen("petnames.txt", "w");

    if(fptr==NULL)
    {
        printf("Error\n");
    }

    else
    {
        while(petRecord != NULL)
        {
            fprintf(fptr, "\nPet Name: %s\nAge: %d\n", petRecord->name, petRecord->age);
            petRecord = petRecord->next;
        }
    }

    fclose(fptr);
    }

int main()
{ 
    int count, i;
    printf("How many pets do you have? ");
    scanf("%d", &count);

    for(i=0; i<count; i++)
    {
        if(i==0)
        {
            petRecord = malloc(sizeof(struct Node));
            newRecord = petRecord;
        }
        else
        {
            newRecord->next = malloc(sizeof(struct Node));
            newRecord = newRecord->next;
        }
        newRecord->name = malloc(50*sizeof(char));
        printf("Name of Pet: ");
        scanf("%s", newRecord->name);
        printf("Age of Pet: ");
        scanf("%d", &newRecord->age);
    }
    newRecord->next = NULL;
    printf("\n\n");
    printPetRecord();
    writeToFile();
}

【问题讨论】:

  • 您是否尝试将其打印在标准输出上?
  • 不要使用全局变量。
  • @Katrina:当您直接使用全局变量进行迭代时,您丢失了列表头

标签: c linked-list


【解决方案1】:

您的函数 printPetRecord() 将指针设置为空。

在 printPetRecord() 里面做这样的事情:

struct Node * iterator = petRecord;

然后使用迭代器进行迭代。

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

struct Node {
    char *name;
    int age;
    struct Node *next;
};

struct Node * petRecord;
struct Node * newRecord;

void printPetRecord()
{
    struct Node * iterator = petRecord;
    while(iterator != NULL)
    {
        printf("Name of Pet: %s\n", iterator->name);
        printf("Age of Pet: %d\n", iterator->age);
        iterator=iterator->next;
    }
}

void writeToFile()
{
    FILE * fptr;
    fptr = fopen("petnames.txt", "w");
    struct Node * iterator = petRecord;

    if(fptr==NULL)
    {
        printf("Error\n");
    }

    else
    {
        while(iterator!= NULL)
        {
            fprintf(fptr, "\nPet Name: %s\nAge: %d\n", iterator->name, iterator->age);
            iterator= iterator->next;
        }
    }

    fclose(fptr);
    }

int main()
{
    int count, i;
    printf("How many pets do you have? ");
    scanf("%d", &count);

    for(i=0; i<count; i++)
    {
        if(i==0)
        {
            petRecord = malloc(sizeof(struct Node));
            newRecord = petRecord;
        }
        else
        {
            newRecord->next = malloc(sizeof(struct Node));
            newRecord = newRecord->next;
        }
        newRecord->name = malloc(50*sizeof(char));
        printf("Name of Pet: ");
        scanf("%s", newRecord->name);
        printf("Age of Pet: ");
        scanf("%d", &newRecord->age);
    }
    newRecord->next = NULL;
    printf("\n\n");
    printPetRecord();
    writeToFile();
}

执行:

> gcc -o main main.c
> ./main
How many pets do you have? 2
Name of Pet: a
Age of Pet: 2
Name of Pet: b
Age of Pet: 3


Name of Pet: a
Age of Pet: 2
Name of Pet: b
Age of Pet: 3
> cat petnames.txt

Pet Name: a
Age: 2

Pet Name: b
Age: 3

【讨论】:

  • 这再次表明全局变量是邪恶的。
  • 通过这样做 [struct Node * iterator = petRecord],我创建了一个新节点,它指向我的链表的第一个值的地址。所以要将数据写入 txt 文件,我会这样做: while(iterator != NULL) { fprintf(fptr, "\nPet Name: %s\nAge: %d\n", iterator->name, iterator- >年龄);迭代器=迭代器->下一个;我的文件中仍然没有任何数据:/
  • 为我工作 :)
  • 我再去看看!谢谢大家:)
【解决方案2】:

3 年 7 个月后,不知何故,我在解决将 linked list 的数据写入 .txt 文件的问题时遇到了这个问题。我来这里寻求解决我的问题,但这个问题没有接受任何答案。所以在这里我将尝试回答这个问题。

  1. 程序中不需要全局变量。
  2. 向程序中的函数发送一些参数,这将使您的任务变得更容易。
  3. 在这些函数中进行迭代时,您将丢失 head 结构变量,因为这样做 petRecord = petRecord-&gt;next 和 main newRecord = newRecord-&gt;next。这是因为全局变量而发生的。因此,为避免这种情况,您需要每次在被调用函数中声明一个 local 类型为 struct Node 的指针变量。
  4. 不要这样做:newRecord-&gt;name = malloc(50*sizeof(char));,如果您知道 char 数组的确切大小而不是这样做,请将您的 struct 模板修改为 char name[50]。这比使用指针和动态分配要容易得多,因为在后一种情况下,您需要格外小心和预防。
  5. main()函数中打开要写入data的文件,并将其发送到函数writeToFile()
  6. strings 打交道时应格外小心。
  7. 在分配内存或打开文件时检查错误是值得的。因此,每当您在程序中执行任何这些操作时,最好检查在操作过程中发生的任何错误。

为什么不试试这个程序:

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

typedef struct Node {
    char name[50];
    int age;
    struct Node *next;
}Node;

// user-defined functions
void printPetRecord(Node *head);
void writeToFile(FILE *fptr, Node *head);

// main()
int main(void)
{
    int count, i;
    Node *petRecord, *newRecord;
    FILE *fp;

    if( (petRecord = malloc(sizeof(Node))) == NULL )
    {
        fprintf(stderr, "Unable to allocate memory.\n");
        exit(2);
    }
    newRecord = petRecord;
    printf("How many pets do you have? ");
    scanf("%d", &count);

    for(i = 0; i < count; i++)
    {
        printf("Name of Pet: ");
        scanf("%50s", newRecord->name);
        printf("Age of Pet: ");
        scanf("%d", &newRecord->age);
        if(i == count-1)
        {
            newRecord->next = NULL;
        }
        else
        {
            if( (newRecord->next = malloc(sizeof(Node))) == NULL)
            {
                fprintf(stderr, "Memory Unavailable.\n");
                exit(3);
            }
        }
        newRecord = newRecord->next;
    }
    printf("\n\n");
    // Modified arguments
    printPetRecord(petRecord);

    // Open file before sending to writeToFile
    if(!(fp = fopen("petname.txt", "w")))
    {
        fprintf(stderr, "Unable to open file \"petname.txt\"\n");
        exit(1);
    }
    // Modified arguments
    writeToFile(fp, petRecord);
    
    fclose(fp);
    return 0;
}

// function to print linked_list
void printPetRecord(Node *head)
{
    if(head->next != NULL)
    {
        printf("Name of Pet: %s\nAge of Pet: %d\n", head->name, head->age);
        printPetRecord(head->next);
    }
    else
        printf("Name of Pet: %s\nAge of Pet: %d\n", head->name, head->age);
}

// function to print list to file
void writeToFile(FILE *fptr, Node *head)
{
    if(head->next != NULL)
    {
        fprintf(fptr, "\nPet Name: %s\nAge: %d\n\n", head->name, head->age);
        writeToFile(fptr, head->next);
    }
    else
        fprintf(fptr, "\nPet Name: %s\nAge: %d\n\n", head->name, head->age);
}

输出(在控制台上):

How many pets do you have? 3
Name of Pet: Tommy
Age of Pet: 3
Name of Pet: Julia
Age of Pet: 4
Name of Pet: Hedgehog
Age of Pet: 5


Name of Pet: Tommy
Age of Pet: 3
Name of Pet: Julia
Age of Pet: 4
Name of Pet: Hedgehog
Age of Pet: 5

输出(petname.txt 文件内):


Pet Name: Tommy
Age: 3


Pet Name: Julia
Age: 4


Pet Name: Hedgehog
Age: 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2016-03-02
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多