Pregunta

I have the following code in C. I run it at FreeBSD. I compile it as cc -o bbb bb.c. Then run and get the output

$ ./bbb
-1    
stat: No such file or directory

This is the Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>


int main() {
    struct stat *st;
    int stat_code =0;
    stat_code = stat("/", st);
    printf("%d\n", stat_code);
    perror("stat");
    return 0;
}
¿Fue útil?

Solución 2

This the the function prototype for stat() from man 2 stat

int stat(const char *path, struct stat *buf);

Your code will get segmentation fault, because address of structure variable need to pass in stat() function.

Code:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>

   int main() {
        struct stat st;
        int stat_code =0;
        stat_code = stat("test.txt", &st);
        printf("%d\n", stat_code);
        perror("stat");
        return 0;
    }

above will help you. For reference

man 2 stat

Otros consejos

int stat(const char *restrict path, struct stat *restrict buf);

The stat() function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file.

In your code stat("/", st); is path for directory only.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top