Linux/ubuntu/No stat() 中有此类文件或目录,但该文件存在

Linux/ubuntu/No such file or directory in stat() but the file is exist

我制作了打印当前目录中文件大小或目录大小的程序。 所以我使用 stat() 使用文件的绝对路径。并且文件存在!! 然而,每当我执行程序时,都会出现错误 'no such file or directory',尽管该文件存在。当前目录是 project2。 我想获取项目 2 中 'check' 文件的大小。

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);

当我像这样更改 stat() 时,

if(stat("/home/minky/project/project2/check", statbuf) < 0){
            fprintf(stderr, "stat error\n");
            exit(1);
    }

程序有效。它打印文件的大小。

您的代码准备相对路径并假定程序 运行 与文件所在的工作目录相同。尝试从您的程序打印当前目录以确定它尝试解析文件路径的实际目录。

假设修改你的程序:

#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;
}

让我们运行如下,假设代码在/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