Linuxubuntu在stat()中没有这样的文件或目录,但文件是存在的。

问题描述 投票:0回答:2

我做了一个打印当前目录下的文件大小或目录大小的程序,所以我用stat()使用了文件的绝对路径,而且文件存在!!但是,每当我执行程序时,就会出现 "no such file or directory "的错误,尽管文件存在。当前目录是project2.我想得到project2中'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);
    }

程序工作了,它打印文件的大小,我做了一个程序来打印当前目录下的文件大小或目录大小。

c ubuntu-18.04 absolute-path stat realpath
2个回答
0
投票

你的代码准备的是相对路径,并且假设程序运行的工作目录与文件所在的目录相同。试着从你的程序中打印出当前目录,以确定它试图解析文件路径的实际目录。

假设修改你的程序。

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

让我们按照下面的方式运行它 假设代码在以下目录下 /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
© www.soinside.com 2019 - 2024. All rights reserved.