-
Pointer problem
Hi I am new in C programming and I am facing a problem with the pointer in this program that takes a file path and returns stats about the file by using the stat system call :
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
void serious_error(char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
/* Fonction principale */
int main(int argc, char **argv) {
struct stat status, *buffer;
int r;
r = stat(argv[1], buffer);
if (r < 0)
serious_error("Stat");
printf("File %s: mode: %X size: %ld owner: %d\n",
argv[1], buffer->st_mode, buffer->st_size, buffer->st_uid);
exit(EXIT_SUCCESS);
}
Can someone help me solving this please ?
-
You need buffer to point to status. Or, you can just pass &status instead of passing buffer, and then use status.st_mode etc.
-
ok, but how can I make buffer pointing to status ?
-
Hi Ramsis94.
You can just use status, but pass it's address like &status.
Code:
#define _DEFAULT_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
void serious_error(char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: get_stats FILENAME\n");
return EXIT_FAILURE;
}
struct stat status;
if (stat(argv[1], &status) < 0)
serious_error("stat");
struct passwd *pass = getpwuid(status.st_uid);
const char *type = "other";
if (S_ISREG(status.st_mode))
type = "regular";
else if (S_ISDIR(status.st_mode))
type = "dir";
else if (S_ISLNK(status.st_mode))
type = "symlink";
printf("File: %s type: %s mode: %o size: %ld owner: %s (%d)\n",
argv[1], type, (unsigned)(0777 & status.st_mode), (long)status.st_size,
pass->pw_name, status.st_uid);
return 0;
}
-
thank you a lot John, it worked. But I am realy interested in solving this by making buffer pointing to status. Do u have any idea how to do this ?
-
There is no advantage in that, in fact it just makes it more complicated, but you could say:
Code:
struct stat status, *pstatus = &status;
stat(argv[1], pstatus);
printf("%ld", (long)pstatus->st_size);
-
Great ! that's what I needed. thank u very much