检测文件扩展名时出现分段错误

Segmentation Fault when detecting file extension

我不知道我的程序哪里有问题,我使用了调试器,但它没有指定错误在哪一行

#define _POSIX_SOURCE //pour nofile

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



int main (void)
{
    const char *description;
    magic_t cookie;

    FILE* Texte= NULL;
    if(NULL == (Texte = fopen("chaines", "r")) )
    { // then fopen failed
    perror( "fopen failed for chaines for read");
    exit( EXIT_FAILURE );
    }

    // implied else, fopen successful
    cookie = magic_open(MAGIC_NONE);
    description = magic_descriptor(cookie, fileno(Texte));
    printf("%s\n", description);
return 0;
}

And this is my debuger result
    Starting program: /home/hamza/Bureau/Projet_suffixe/suffixe_db 
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7888e41 in ?? () from /lib/x86_64-linux-gnu/libc.so.6

谢谢。

你应该检查magic_openmagic_descriptor是否成功,并通过magic_load()函数加载魔法数据库。

#define _POSIX_SOURCE //pour nofile

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

int main (void)
{
    magic_t cookie;

    FILE* Texte= NULL;
    if (NULL == (Texte = fopen("chaines", "r")) )
    { // then fopen failed
        perror( "fopen failed for chaines for read");
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful
    cookie = magic_open(MAGIC_NONE);
    if (cookie != NULL)
    {
        /* you should load the database */
        if (magic_load(cookie, NULL) == 0)
        {
            const char *description;

            description = magic_descriptor(cookie, fileno(Texte));
            if (description != NULL)
                printf("%s\n", description);
            else
                printf("Unknown\n");
            magic_close(cookie); // cleanup resources
        }
        else
            fprintf(stderr, "error loading the magic database\n");
    }
    fclose(Texte); // cleanup resources

    return 0;
}

这不会崩溃。

还有一个magic_file函数,传cookie和文件名就可以直接写成

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

int main (void)
{
    magic_t cookie;

    cookie = magic_open(MAGIC_NONE);
    if (cookie != NULL)
    {
        /* you should load the database */
        if (magic_load(cookie, NULL) == 0)
        {
            const char *description;

            description = magic_file(cookie, "chaines");
            if (description != NULL)
                printf("%s\n", description);
            else
                printf("Unknown\n");
            magic_close(cookie);
        }
        else
            fprintf(stderr, "error loading the magic database\n");
    }
    return 0;
}