i made program that prints file size or directory size in current directory. so i used stat() using absolute path of file. and file exists!! however, whenever i executed program, there is a error 'no such file or directory', although the file exists. current directory is project2. and i want to get size of 'check' file in project2.
char * filename = "check";//the file name that i have to print file size.
char * rPath = malloc(BUF_LEN);
char * realPath = malloc(BUF_LEN);
//make relative path
strcat(rPath, ".");
strcat(rPath, "/");
strcat(rPath, filename);
realpath(rPath, realPath);//get absolute path
if(stat(realPath, statbuf) < 0){
fprintf(stderr, "stat error\n");
exit(1);
}
printf("%ld\n", statbuf->st_size);
and when i change stat() like this,
if(stat("/home/minky/project/project2/check", statbuf) < 0){
fprintf(stderr, "stat error\n");
exit(1);
}
the program works. it prints size of the file.
Your code preparing relative path and assumes that the program runs with the same working directory as the file resides. Try print the current directory from your program to determine the actual directory it's trying to resolve the file path.
Assuming modification of your program:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/limits.h>
#define BUF_LEN PATH_MAX
int main()
{
char * filename = "check";//the file name that i have to print file size
char * rPath = malloc(BUF_LEN);
char * realPath = malloc(BUF_LEN);
char current_dir[BUF_LEN];
struct stat statbuf;
//make relative path
sprintf(rPath, "./%s", filename);
// Get current directory
getwd(current_dir);
printf("%s\n",current_dir);
realpath(rPath, realPath);//get absolute path
if(stat(realPath, &statbuf) < 0){
fprintf(stderr, "stat error\n");
} else {
printf("%ld\n", statbuf.st_size);
}
free(rPath);
free(realPath);
return 0;
}
Let's run it as following, assuming the code is in /tmp/main.c
:
$ cd /tmp
$ gcc main.c
-------here be some warnings regarding getwd()
$ echo 1234567890 >check
$ ./a.out
/tmp
11
$ mkdir smth
$ cd smth
$ ../a.out
/tmp/smth
stat error