【问题标题】:Unexpected result when saving struct members to .txt file in C将结构成员保存到 C 中的 .txt 文件时出现意外结果
【发布时间】:2018-06-20 06:10:54
【问题描述】:

我在尝试将信息从我的程序保存到 .txt 文件(或任何文件)时遇到了一些问题。我已经多次查看我的代码,但似乎找不到问题。最初我认为可能存在某种形式的内存泄漏(虽然我不知道内存泄漏的后果,所以我不能确定)。

我想澄清一下,这是一项学校作业,毕竟我是来学习的,所以不要轻易给我答案!

这项任务是我们的最后一个任务,也是我们最大的任务。我们正在创建一个带有结构的购物清单。当我尝试使用 struct 成员将信息保存到 .txt 文件中时(如果需要,可以稍后将它们加载到程序中),问题就开始了。我知道代码可能看起来很可怕而且很伤眼,但请耐心等待。

这是我的“保存”功能。这是非常基本且非常可怕的。

void saveList(struct GList *grocery)
{
    char file[20];
    FILE *fp;

    printf("What do you want to save the list as? (Don't include file extension): ");
    scanf("%s", file);

    fp = fopen(strcat(file, ".txt"), "w");

    for (int i=0; i<grocery->Items; i++)
    {
        printf("%s %f %s\n", grocery->list[i].name, grocery->list[i].amount, grocery->list[i].unit);
        fprintf(fp, "%s %f %s\n", grocery->list[i].name, grocery->list[i].amount, grocery->list[i].unit);
    }
    fclose(fp);
}

这是我在程序中输入的内容(添加项目时):

Name of the item: Avocado
Unit: kg
Amount: 10

这是保存到我的 .txt 文件中的内容(它没有显示,但第一行总是包含一些奇怪的符号)。

  10.000000 kg
milk 10.000000 litres

同样的问题总是出现;第一个项目名称(例如鳄梨)显示为一些奇怪的符号。

这是我的完整代码,问题可能出在此处。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>

struct Grocery {
    char name[20];
    char unit[20];
    float amount;
};

struct GList {
    size_t Items;
    struct Grocery *list;
};

int addGrocery();
void printList();
void hQuit();
void inputError();
void removeItem();
void changeItem();
void saveList();

int main()
{
    struct GList glist;
    glist.Items = 1;

    size_t menuChoice = 0;
    char cont = 'y';

    if((glist.list = malloc(sizeof(glist.list))) == NULL)
        return ENOMEM;

    puts("Welcome to your Grocery List Manager");

    do
    {
        printf("\n- - - - - - - - - - -\n[1] Add an item\n[2] Print grocery list\n[3] Remove a grocery\n[4] Edit a grocery\n[5] Save your list\n[6] Load a list\n[7] Quit\n\nPlease choose action: ");
        if(!scanf("%u", &menuChoice))
            return EIO;

        putchar('\n');

        switch(menuChoice)
        {
            case 1:
                addGrocery(&glist);
                break;
            case 2:
                printList(&glist);
                break;
            case 3:
                removeItem(&glist);
                break;
            case 4:
                changeItem(&glist);
                break;
            case 5:
                saveList(&glist);
                break;
            case 6:
                //Load shopping list
                break;
            case 7:
                hQuit(&glist);
                break;
            default:
                inputError();
                break;
        }
    } while (cont == 'y');

    //free(grocery);

    return 0;
}

int addGrocery(struct GList *grocery)
{
    printf("Name of the grocery: ");
    if(!scanf("%s", grocery->list[grocery->Items].name))
        return EIO;

    printf("Unit: ");
    if(!scanf("%s", grocery->list[grocery->Items].unit))
        return EIO;

    printf("Amount: ");
    if(!scanf("%f", &grocery->list[grocery->Items].amount))
        return EIO;

    printf("You have added %f %s of %s into your list!\n\n", grocery->list[grocery->Items].amount, grocery->list[grocery->Items].unit, grocery->list[grocery->Items].name);

    (grocery->Items)++;
    grocery->list = realloc(grocery->list, grocery->Items * sizeof(grocery->list));

    if(grocery->list == NULL)
        return ENOMEM;

    return 1;
}

void printList(struct GList *grocery)
{
    if ((grocery->Items - 1) > 0)
        printf("You have added %d item(s) into your list!\n", grocery->Items - 1);
    else
        printf("You have no items in your list!\n");

    for (int i=1; i<grocery->Items; i++)
    {
        printf("[%d] %-10s %.1f %s\n", i, grocery->list[i].name, grocery->list[i].amount, grocery->list[i].unit);
    }
    putchar('\n');
}

void removeItem(struct GList *grocery)
{
    size_t index = 0;
    printf("Which item would you wish to remove from the list? ");
    scanf("%u", &index);
    printf("\nYou have removed %s from your grocery list!", grocery->list[index].name);
    for (int i=(int)index; i < grocery->Items; i++)
        grocery->list[i] = grocery->list[i+1];

    (grocery->Items)--;
}

void changeItem(struct GList *grocery)
{
    size_t index = 0;
    printf("Which item would you like to edit the amount of? ");
    scanf("%d", &index);
    printf("\nCurrent amount: %.1f %s\nEnter new amount: ", grocery->list[index].amount, grocery->list[index].unit);
    scanf("%f", &grocery->list[index].amount);
    printf("\nYou changed the amount to %.1f!\n", grocery->list[index].amount);
}

void hQuit(struct GList *grocery)
{
    puts("*-*-* Thank you for using the Grocery List! *-*-*");
    free(grocery->list);
    exit(0);
}

void inputError(struct GList *grocery)
{
    puts("No such option. Please try again!\n");
}

void saveList(struct GList *grocery)
{
    char file[20];
    FILE *fp;
    printf("What do you want to save the list as? (Don't include file extension): ");
    scanf("%s", file);
    fp = fopen(strcat(file, ".txt"), "w");
    for (int i=0; i<grocery->Items; i++)
    {
        printf("%s %f %s\n", grocery->list[i].name, grocery->list[i].amount, grocery->list[i].unit);
        fprintf(fp, "%s %f %s\n", grocery->list[i].name, grocery->list[i].amount, grocery->list[i].unit);
    }

    fclose(fp);
}

如果我的代码在某些地方看起来很奇怪(为什么会有一个 void inputError()?),那是因为我们的老师为我们的作业设置了一些非常奇怪的规则。

请随意抨击我的代码。

【问题讨论】:

  • 第一个明显的问题:glist.list 显然是一个指向杂货对象的指针数组,但您只是为一个对象分配内存。第二: addGrocery 假设存在一个杂货项目,但你第一次调用它时显然没有创建任何杂货项目,所以你的 scanf 正在进入随机内存。事实上,我没有看到你在任何地方为任何杂货分配内存。
  • @LeeDanielCrocker 我们的老师:创建一个指针,您将为其分配内存(作为数组工作)。当您向列表中添加新项目时,您将沿途扩展所需的内存 (realloc())。我不明白 addGrocery() 如何假设内存中已经有一个项目?我错过了什么吗?
  • 一如既往,T*p=[m/c/re]alloc(sizeof T*) 是错误的。
  • 指针列表是你需要内存的一件事。但是您还需要为它们指向的每个结构提供内存。另一种方法是将 GList.list 声明为零长度数组而不是指针,然后在整个结构单元中分配。
  • @LeeDanielCrocker 所以其中一项任务不是使用数组,而是将指针与 malloc() 和 realloc() 一起使用。我认为 malloc(n * sizeof(list)) 与 list[n] 基本相同,只是它是动态内存。

标签: c file struct printf


【解决方案1】:

问问自己,“C 是使用基于 0 还是基于 1 的数组索引”?

调用addGrocery时,传入glist的地址,

addGrocery(&glist);

当您第一次调用 addGrocery 时,glist 的第一个/初始值是什么?在添加第一项之前,此列表包含多少项?这是一个“列表”,还是一个“数组”?

这是你的 main 函数的前几行(它回答了这个问题),

int main()
{
    struct GList glist;
    glist.Items = 1;

    if((glist.list = malloc(sizeof(glist.list))) == NULL)
        return ENOMEM;

考虑定义一个函数(构造函数)来创建初始(空)列表。以及向列表添加元素的函数。

您的 addGrocery 函数将输入数据和将数据添加到列表中。考虑一个仅收集输入的函数,然后调用该函数将数据添加到列表中。

int addGrocery(struct GList *grocery)
{
    printf("Name of the grocery: ");
    //what is the value of grocery-Items the first time this is called?
    if(!scanf("%s", grocery->list[grocery->Items].name))
        return EIO;

    //Consider something that creates a grocery list item (does malloc)
    //then appends that list item to the list

    //then this check would not be needed (well, it would change)
    if(grocery->list == NULL)
        return ENOMEM;

提示:您是否要添加到第一个列表元素?

但是还有一个更大的问题。您是使用数组还是列表来存储 struct Grocery 商品?您将列表声明为指针,并在 main.xml 中对其进行初始化。您是否分配了一些项目的数组,或者您想要一个项目列表? struct Grocery 类型没有指针,因此您可能不需要“列表”,而是需要“数组”(命名很重要)。

struct GList {
    size_t Items;
    struct Grocery *list;
};

因为您的 addGrocery 函数使用数组索引,假设您想要一个 Grocery 商品数组,但您创建了多少?你在说哪一个?

(这些问题应该为您指明正确的方向)

【讨论】:

  • 这些问题确实为我指明了正确的方向!非常感谢您的帮助,您的帖子给了我很多思考,但现在我对这个问题有了更好的理解:D
【解决方案2】:

首先,我相信你的老师会多次告诉你不要使用幻数:

char file[PATH_MAX];

为了您的程序未来的计算合理性,您可能希望避免溢出此缓冲区:

if (snprintf(NULL, 0, "%s.txt", file) >= PATH_MAX - 1) {
    fputs("Filename too long!", stderr);
    exit(EXIT_FAILURE);
}

if (scanf("%s", grocery->list[grocery->Items].name) == 1)

在您阅读the scanf manual(这是我们作为软件开发人员的工作的一部分)之前,您不会知道自己在错误地使用scanf。事实上,即使粗略一瞥,你似乎也看不出你做错了什么。

确实,作为软件开发人员,我们不仅必须仔细阅读其他人编写的手册、错误消息、代码(这可能无法很好地反映低质量的 cmets)。

检查 scanf 是否返回 0 是确定是否读取了 0 个元素的好方法,但不是确定 EOF 或其他文件访问错误是否发生的好方法。

你能弄清楚为什么我(正确地)与 1 进行比较吗?如果您想使用与scanf 的单个比较从stdin 读取两个 值,您应该将返回值与哪个数值比较?


void *temp = realloc(grocery->list, grocery->Items * sizeof *grocery->list);
if (temp == NULL)
    return ENOMEM;
grocery->list = temp;

你不会知道你正在使用realloc incorre...阅读the realloc manual yada ... yada ...等等等等

我在这里做了另一个修改:你漏掉了一个星号! D'oh!看看你能不能找到它:)

确实,作为软件开发人员,我们不仅必须仔细阅读其他人编写的手册、错误消息、代码(这可能无法很好地反映低质量的 cmets)。

因此,我们必须从手册中进行一些推断,以确定realloc 何时可能不是free 旧指针,然后再覆盖它(从而导致内存泄漏)。

你能弄清楚我为什么使用temporary 变量吗(应该是这样)?

同样,您在这里错过了另一个星号:

if((glist.list = malloc(sizeof glist.list[0])) == NULL)

对不起,我忍不住让它更明显一点……你应该记下遵循这些模式:

pointer = malloc(count * sizeof *pointer);               // -- the `malloc` pattern; pointer could be NULL, so needs checking
void *temp = realloc(pointer, count * sizeof *pointer);  // -- the `realloc` pattern; temp could be NULL (in which case you need to deal with `pointer`)

记住这两种模式,你就不会再犯这些错误了。

当我们讨论列表时,空列表包含 0 个项目,对吧?

glist.Items = 0;

附:你听说过valgrind吗?...

【讨论】:

  • 不,我没有听说过 valgrind,但我真的很感谢你花时间经历这样的事情!我学到了很多关于我自己容易犯的错误,我知道很多这些事情,但是由于某种原因,我在尝试实施它时做错了,我需要更多地学习:D 非常感谢!
  • 好吧,现在您已经听说过valgrind... 您可以通过谷歌搜索“valgrind 替代品”找到其他操作系统的替代品。问题是,您是否要利用 Google 的力量来找到能够帮助您发现并在几分钟内解决此类问题的知识,而不是浪费数小时寻找基本的拼写错误。 ..?
猜你喜欢
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
相关资源
最近更新 更多