我需要读取一个文件并将文件中的数据存储到一个结构中。文件的第一行包含必须动态分配的结构数组的大小。

    4
    12/04/2010
    Interview went well I think, though was told to wear shoes.
    18/04/2010
    Doc advised me to concentrate on something... I forget.
    03/05/2010
    Was asked today if I was an art exhibit.
    19/05/2010
    Apparently mudcakes not made of mud, or angry wasps.

我将在Windows中完美地运行我的代码,但是当我在Unix环境中运行时,它会显示分段错误(核心转储)。我确实使用了valgrind来检查内存泄漏,这就是结果
    ==4344== Invalid read of size 1
    ==4344==    at 0x407F842: ____strtol_l_internal (strtol_l.c:298)
    ==4344==    by 0x407F606: strtol (strtol.c:108)
    ==4344==    by 0x407C87E: atoi (atoi.c:27)
    ==4344==    by 0x8048837: main (in /home/admininistrator/ucp/p6/gg)
    ==4344==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
    ==4344==
    ==4344==
    ==4344== Process terminating with default action of signal 11 (SIGSEGV)
    ==4344==  Access not within mapped region at address 0x0
    ==4344==    at 0x407F842: ____strtol_l_internal (strtol_l.c:298)
    ==4344==    by 0x407F606: strtol (strtol.c:108)
    ==4344==    by 0x407C87E: atoi (atoi.c:27)
    ==4344==    by 0x8048837: main (in /home/admininistrator/ucp/p6/gg)
    ==4344==  If you believe this happened as a result of a stack
    ==4344==  overflow in your program's main thread (unlikely but
    ==4344==  possible), you can try to increase the size of the
    ==4344==  main thread stack using the --main-stacksize= flag.
    ==4344==  The main thread stack size used in this run was 8388608.
    ==4344==
    ==4344== HEAP SUMMARY:
    ==4344==     in use at exit: 1,396 bytes in 3 blocks
    ==4344==   total heap usage: 3 allocs, 0 frees, 1,396 bytes allocated
    ==4344==
    ==4344== LEAK SUMMARY:
    ==4344==    definitely lost: 0 bytes in 0 blocks
    ==4344==    indirectly lost: 0 bytes in 0 blocks
    ==4344==      possibly lost: 0 bytes in 0 blocks
    ==4344==    still reachable: 1,396 bytes in 3 blocks
    ==4344==         suppressed: 0 bytes in 0 blocks
    ==4344== Rerun with --leak-check=full to see details of leaked memory
    ==4344==
    ==4344== For counts of detected and suppressed errors, rerun with: -v
    ==4344== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
    Segmentation fault (core dumped)

这是我的密码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"struct.h"

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        printf("You have enter less arguments.\n");
    }
    else if (argc > 2)
    {
        printf("You have enter too many arguments.");
    }
    else
    {
        FILE *file;
        Diary *res;
        Diary *res2;
        char line[102];
        int i, size, k, l, choice;
        int day, month, year;
        /* int d[10],m[10],y[10];*/
        char as[102];
        char* oken;
        char* yoken;
        char* coken;
        oken = NULL;
        yoken = NULL;
        coken = NULL;

        i = 0;

        file = fopen("struct.txt", "r");
        if (file == NULL)
        {
            perror("Error opening file\n.");
        }
        else
        {
            fscanf(file, "%d", &size);
            res = (Diary*) malloc(size * sizeof(Diary));
            res2 = (Diary*) calloc((5), sizeof(Diary));

            while (fgets(line, sizeof(line), file) != NULL)
            {
                oken = strtok(line, "/");
                if (oken != NULL)
                {
                    res2[i].day= atoi(oken);
                    coken = strtok(NULL, "/");
                    if (oken != NULL)
                    {
                        res2[i].month = atoi(coken);
                        yoken = strtok(NULL, "\n ");
                        if (coken != NULL)
                        {
                            /*printf("%s",yoken);*/
                            res2[i].year = atoi(yoken);

                            fgets(as, 102, file);
                            strncpy(res2[i].entry, as, 102);
                        }
                    }
                }
                i++;
            }
            k = 1;
            l = 0;

            while (l < size)
            {
                res[l].day = res2[k].day;
                res[l].month = res2[k].month;
                res[l].year = res2[k].year;
                strncpy(res[l].entry, res2[k].entry, 102);
                k++;
                l++;
            }

            choice = atoi(argv[1]);

            printf("%d-%02d-%02d:%s",res[choice].year, res[choice].month,res[choice].day,res[choice].entry);

            free(res2);
            free(res);
        }

        fclose(file);
    }

    return 0;
}

我需要将文件中的所有数据读取到结构中,并在用户需要输入时将其打印出来。我试着一部分一部分地调试,结果发现是部分while( fgets( line, sizeof( line ), file) != NULL)导致了问题。但我不知道怎么解决。
Mystruct.h如下:
   typedef struct journal{
        int day;
        int month;
        int year;
        char entry[1024];
   } Diary;

最佳答案

我不太明白你想达到的目标,但这里有几个问题。
您可能不需要day month year变量。
这条线
day = atoi(oken);
应该是
res2[i].day = atoi(oken);
读取size的行有问题
fscanf(file, "%d", &size)
它读取一个整数,但不读取后面的换行符
你得把这个改成
fscanf(file, "%d\n", &size)
或者使用fgets
由于后面有一个换行符,下次调用gets时,您将获得一个只包含换行符的字符串。
您的strtok调用和空检查不同步。第一个,因为oken是可以的。但是,然后执行返回strtokcoken操作,但对oken执行空检查,最后执行返回strtokyoken操作,对coken执行空检查。在这三种情况下,对strtok的调用之后应该对返回值进行空检查(与oken的情况一样)。
我不明白while (l < size)循环的目的(可能是因为上面描述的新线处理不当?)。分配5个结构,从structs.txt读取4到res2(元素0到3),然后将res2的元素1到4复制到res的元素0到3。这意味着res2的元素0不会被复制,而全部为零的元素4也会被复制。
车祸的原因是第3点和第4点的结合。
我建议不要使用atoi,因为它不会进行错误检查。除非您确定字符串包含格式正确的整数,否则使用它是不安全的。如果希望代码健壮,则需要添加更多的错误检查,例如,检查malloccalloc的返回值。

10-06 10:23