Pobranie nazwy katalogu ze ścieżki - znów seg fault

0

Dlaczego ten kod daje seg fault? I jak się go pozbyć?:(

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <dirent.h>
#include <string.h>

int main()
{
        const char* path = "/home/user/Pulpit/plik.txt";
        char answer[255];
        strcpy(answer, (char*)dirname(path));
        printf("%s\n", answer);
        return 0;
}
0

Zobacz specyfikację funkcji dirname: http://linux.die.net/man/3/dirname
Funkcja oczekuje char * a dajesz jej const char *. AFAIK ze względów historycznych w C nie powoduje to błędu kompilacji ale z pewnością to co robisz jest błędne (o czym świadczy SIGSEGV).
Poza tym nie dodałeś nagłówka <libgen.h>.

0
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <dirent.h>
#include <string.h>
#include <libgen.h>

char *getDirpath(char *path)
{
        char *dirc, *dname;
        dirc = strdup(path);
        dname = (char*)dirname(dirc);
        free(dirc);
        return dname;
}

int main()
{
        char* path = "/etc/passwd.txt";
        char *dirc = NULL;
        dirc = getDirpath(path);

        printf("dirname=%s\n", dirc);

        return 0;
}

No właśnie poprawiłem to - i dalej nic. Tym razem z pamięcią jest ok, ale nie wyświetla mi nic :/

0

Przeczytaj dokładnie specyfikację jeszcze raz.
"Alternatively, they may return a pointer to some part of path, so that the string referred to by path should not be modified or freed until the pointer returned by the function is no longer required."

0

Ahaaa! Usunąłemto free i działa, dziękuję! ;)

0

To nie rozumiem teraz - mam zwolnić pamięc dopiero po wyświetleniu? Ale z maina nie mam dostępu do zadeklarowanej lokalnie zmiennej?

0
int main()
{
        char answer[255];
        strcpy(answer, "/home/user/Pulpit/plik.txt");
        printf("%s\n", dirname(answer));
        return 0;
}
0

@Azarien - ok to jest dobrze, ale jak z tego zrobić funkcję ...?

0

Albo bez dodatkowego kopiowania: char answer[] = "/home/user/Pulpit/plik.txt";.

1 użytkowników online, w tym zalogowanych: 0, gości: 1