且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法读取 C 中的文本文件

更新时间:2023-02-20 10:34:01

大部分的困惑来自于您在构建列表时的笨拙方式.现在把菜单放在一边——这留给你,让我们专注于构建你的链表.对于初学者来说,由于您没有检查输入函数的返回,所以无法判断您的失败发生在哪里.除非您检查返回,否则您无法正确使用任何输入函数(或任何对代码的持续运行至关重要的函数).您也不希望 硬编码文件名,这就是 int main (int argc, char **argv) 的参数的用途 — 或者您可以使用文件名作为用户输入读取.

Much of the confusion comes from the awkward way you are approaching building your list. Set aside the menu for now -- that is left to you, let's just concentrate on building your linked list. For starters, it's impossible to tell where your failure arises because you fail to check the return of your input function. You cannot use any input function correctly (or any function critical to the continued operation of your code) unless you check the return. You also do not want to Hardcode Filenames, that is what the parameters to int main (int argc, char **argv) are there for — or you can take the filename to read as user-input.

接下来,由于您的数据在文件的输入行中排列,您应该使用面向行的输入函数从文件中读取(例如 fgets() 或 POSIX getline()) 这样您就可以确保每次都使用一整行输入,而未读的内容与使用的格式说明符无关.相反,声明一个足够大小的字符数组来保存文件中的每一行,然后使用 fgets() 读入该数组,然后分成 name, memsizeprice 使用 sscanf()(不要忘记检查返回值)

Next, since your data is arranged in lines-of-input in your file, you should use a line-oriented input function to read from the file (such as fgets() or POSIX getline()) That way you ensure you consume an entire line of input each time and what remains unread does not depend on the format specifier used. Instead, declare a character array of sufficient size to hold each line from your file and then read into that array with fgets() and then separate into name, mem, size, and price using sscanf() (don't forget to check the return)

虽然您可以将打开的 FILE* 指针发送到 builldbytext() 以读取和构建您的列表,但下面让我们采用一种简单的方法从文件中读取main() 中的一个循环,并用每一行的值填充一个临时结构.然后我们可以将指向您的列表的指针的地址以及指向包含数据的临时结构的指针传递给 add() 函数(您的 push())以构建清单.

While you can send your open FILE* pointer to builldbytext() to read and build your list, below let's just take a simple approach and read from the file in a loop in main() and fill a temporary struct with the values from each line. Then we can pass the address of the pointer to your list along with a pointer to the temporary struct containing data to an add() function (your push()) to build the list.

您没有提供您的节点定义,因此出于示例目的,我们将使用:

You didn't provide your node definition, so for purposes of the example we will use:

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

#define NAMSZ  32       /* if you need a constant, #define one (or more) */
#define MAXC 1024

typedef struct node_t {     /* list node */
    char name[NAMSZ];
    double size;
    int mem, price;
    struct node_t *next;
} node_t;

虽然您可以使用前向链来添加节点,但最终会以与文件中的顺序相反的顺序获得节点.您可以使用 headtail 指针在相同的 O(1) 时间内使用 tail 指针按顺序添加,也可以迭代到最后并添加 O(n) 时间.

While you can use forward-chaining to add the nodes, you will end up with your nodes in the reverse order from what you have in the file. You can either use a head and tail pointer to add in order using the tail pointer in the same O(1) time or you can iterate to the end and add in O(n) time.

在每次迭代的末尾添加节点的简单示例是:

A simple example of adding the node at the end iterating each time would be:

 /** add node at end of list */
node_t *add (node_t **head, node_t *tmp)
{
    node_t **ppn = head,                    /* pointer to pointer to head */
            *pn = *head,                    /* pointer to head */
            *node = malloc (sizeof *node);  /* allocate new node */

    if (!node) {                            /* validate allocation */
        perror ("malloc-node");
        return NULL;
    }
    *node = *tmp;                           /* assign tmp struct values */
    node->next = NULL;                      /* set next pointer NULL */

    while (pn) {                            /* iterate to end of list */ 
        ppn = &pn->next;
        pn = pn->next;
    }

    return *ppn = node;                     /* assign & return new node */
}

(注意:通过使用指针到指针,添加第一个或后续节点不需要特殊处理)

(note: by using a pointer-to-pointer there is no special treatment required for adding the first or subsequent nodes)

一个简单的遍历 prn() 和一个删除列表中所有节点的函数 del_list() 完成后可以是:

A simple traversal prn() and a function to delete all nodes in the list del_list() when done could be:

/** print all nodes in list */
void prn (node_t *l)
{
    if (!l) {
        puts ("list-empty");
        return;
    }
    for (node_t *n = l; n; n = n->next)
        printf ("%-16s %3d %5g %d
", n->name, n->mem, n->size, n->price);
}

/** delete all nodes in list */
void del_list (node_t *l)
{
    node_t *n = l;
    while (n) {
        node_t *victim = n;
        n = n->next;
        free (victim);
    }
}

最后,所有需要将您的文件名作为程序的第一个参数读取,或者如果没有提供参数,则从 stdin 读取,以填充列表然后遍历并释放所有分配的内存可以是:

Finally, all that is needed to take your filename to read as the first argument to the program, or read from stdin if no argument is provided, to fill the list and then traverse and free all allocated memory could be:

int main (int argc, char **argv) {

    char buf[MAXC];         /* buffer to hold each line */
    node_t *list = NULL;    /* pointer to list (must initialize NULL) */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {     /* read each line from file */
        node_t tmp;                     /* temporary struct to hold values */
        /* if name, mem, size, price successfully parsed from line */
        if (sscanf (buf, "%s %d %lf %d",
                    tmp.name, &tmp.mem, &tmp.size, &tmp.price) == 4)
            if (!(add (&list, &tmp)))   /* add node to list/validate */
                break;
    }
    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

    prn (list);
    del_list (list);
}

(注意:is_empty() 功能在接收列表的每个函数中处理,只需验证列表中的第一个节点不是 NULL)

(note: the is_empty() functionality is handled in each function that receives the list simply by validating that the first node in the list isn't NULL)

示例使用/输出

使用 dat/phones.txt 文件中的数据,您将收到:

With your data in the file dat/phones.txt, you would receive:

$ ./bin/lls_phones dat/phones.txt
Iphone6           12   9.6 2000000
IphoneX           32  12.3 40000000
SamsungA6         16  11.3 1000000
SamsungNote6      16  12.3 12000000
Iphone5           32   9.5 6000000
Iphone5s          32   9.5 7000000
Iphone6           32   9.3 8000000
Iphone6s          32  11.3 8500000
OppoF5            32   9.3 10000000
OppoE6            32  11.3 20000000
OppoReno          16  12.6 20000000
IphoneSXmax      128  11.3 45000000
Huawei4           64  11.3 20000000
NokiaE5           16   8.6 3000000
SamsungGalaxy     32  12.3 6000000
SamsungNote7      32  12.3 8000000
Iphone7s          32  12.3 10000000
Huawei6           16   9.5 15000000
SamsungNote5      16   8.5 12500000
IphoneX           16  12.3 25000000
Iphone7           24  11.5 25100000

如果您使用前向链接来添加节点,那么它们将以相反的顺序打印.

If you had used forward-chaining to add the nodes, then they would print in the reverse order.

内存使用/错误检查

在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您有 2 个责任:(1) 始终保留一个指向起始地址的指针内存块,(2) 可以在不再需要时释放.

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

您必须使用内存错误检查程序来确保您不会尝试访问内存或超出/超出分配块的范围进行写入,尝试读取或基于未初始化值的条件跳转,最后, 以确认您释放了所有分配的内存.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

对于 Linux valgrind 是正常的选择.每个平台都有类似的内存检查器.它们都易于使用,只需通过它运行您的程序即可.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/lls_phones dat/phones.txt
==17133== Memcheck, a memory error detector
==17133== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==17133== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==17133== Command: ./bin/lls_phones dat/phones.txt
==17133==
Iphone6           12   9.6 2000000
IphoneX           32  12.3 40000000
SamsungA6         16  11.3 1000000
SamsungNote6      16  12.3 12000000
Iphone5           32   9.5 6000000
Iphone5s          32   9.5 7000000
Iphone6           32   9.3 8000000
Iphone6s          32  11.3 8500000
OppoF5            32   9.3 10000000
OppoE6            32  11.3 20000000
OppoReno          16  12.6 20000000
IphoneSXmax      128  11.3 45000000
Huawei4           64  11.3 20000000
NokiaE5           16   8.6 3000000
SamsungGalaxy     32  12.3 6000000
SamsungNote7      32  12.3 8000000
Iphone7s          32  12.3 10000000
Huawei6           16   9.5 15000000
SamsungNote5      16   8.5 12500000
IphoneX           16  12.3 25000000
Iphone7           24  11.5 25100000
==17133==
==17133== HEAP SUMMARY:
==17133==     in use at exit: 0 bytes in 0 blocks
==17133==   total heap usage: 24 allocs, 24 frees, 6,848 bytes allocated
==17133==
==17133== All heap blocks were freed -- no leaks are possible
==17133==
==17133== For counts of detected and suppressed errors, rerun with: -v
==17133== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认您已释放分配的所有内存,并且没有内存错误.

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

检查一下,如果您有任何问题,请告诉我.如果您想更改为 forward-chaining 或使用 tail 指针,请告诉我,我很乐意为您提供进一步的帮助.

Look things over and let me know if you have questions. If you would like to change to forward-chaining or using a tail pointer, let me know and I'm happy to help further.