【问题标题】:C writing a linked list to a fileC将链表写入文件
【发布时间】:2015-03-03 04:13:53
【问题描述】:

我想将链表中的所有整数值写在单独的一行上,我有一个开始但有多个错误,我不知道从哪里开始。

struct ListNode {
    int value;
    struct ListNode * next;
};        

int llist_save(LinkedList * list, char * file_name) {
    ListNode *e = list->head;
    FILE * fd = (file_name, "w");
    while(e != NULL){
        fprintf(fd, "%d\n", e->value);
        e = e->next;
    }
    fclose(fd);
}

【问题讨论】:

标签: c list pointers


【解决方案1】:

使用fopen();试试:

struct ListNode {
      int value;
      struct ListNode * next;
};        

int llist_save(LinkedList * list, char * file_name) {
    struct ListNode *e = list->head;
    FILE * fd = fopen(file_name, "w");
    while(e != NULL){
        fprintf(fd, "%d\n", e->value);
        e = e->next;
    }
    fclose(fd);
}

【讨论】:

    【解决方案2】:

    首先,您需要检查几件事:

    当您声明一个结构时,您基本上是在定义一个自定义用户类型。 因此,每次您要创建该类型的新变量时,都需要将保留字 struture 放在结构名称之前。根据您的代码,这将是这样的:struct ListNode *e;

    然后,您尝试向您的函数发送LinkedList 参数。但是,我认为如果您改为发送 struct ListNode * 参数会更容易,因此您将“知道”列表中的第一个元素是什么。但是,你使用的方法也是有效的。

    谈到函数,你是在声明一个int 返回类型的函数。在您的代码中,您没有放置 return 语句。如果不想返回值,只需将返回类型更改为void。否则,只返回一个整数。

    最后只需使用fopen,这是一个帮助您在系统中打开文件的功能。该函数中的第一个参数是您要打开/创建的文件的名称,第二个参数是您要打开它的“方式”(技术上称为“模式”)。只需发送“w”,即写。

    您说您想在一行中写入值。为此,请在您的打印语句中省略\n 字符并打印' '(空格字符)。

    一些代码:

    struct ListNode 
    {
        int value;
        struct ListNode * next;
    };        
    
    void llist_save(LinkedList * list, char * file_name) 
    {
        struct ListNode *e = list->head;
        FILE * fd = fopen(file_name, "w");
    
        while(e != NULL) {
            fprintf(fd, "%d ", e->value);
            e = e->next;
        }
        fclose(fd);
    }
    

    我的大脑现在不能很好地处理英语;对此感到抱歉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多