首页 > 解决方案 > linux/ubuntu/stat() 使用字符串文字和字符串变量时的工作方式不同

问题描述

我想打印当前目录的文件大小。所以我使用了带有路径和统计结构的 stat() 函数。当前目录是/home/minky/project/project2。我要打印文件大小的文件在 project2 中。当我使用字符串变量时。它返回错误,即“没有这样的文件或目录”。但是,当使用字符串文字时,它可以正常工作(我的意思是,程序打印文件的大小。我想让程序在我输入文件名(标准输入)时打印该文件的大小。 但是在使用时它的工作方式不同字符串变量和字符串文字....我的代码有什么错误吗?(程序太长了,我跳过了不相关的代码)

void do_size(char * command){//ignore this command... this is for another part 


    char * filename;//filename that  i want to print file size.
    struct stat  statbuf;

    char * rPath = calloc(BUF_LEN, sizeof(char));
    char * realPath = calloc(BUF_LEN, sizeof(char));

    filename = token_command[1];//token_command[1] is from another function. 

    //make relative path
    sprintf(rPath, "./%s", filename);

    //make absolute path  
    realpath(rPath, realPath);

    if(stat(realPath, &statbuf) < 0 ){
            fprintf(stderr, "stat error\n");
            printf("%s\n",strerror(errno));
            exit(1);
        }

        printf("%ld %s\n", statbuf.st_size, rPath);




}

但是我像这样更改程序(字符串变量为字符串文字),

if(stat("/home/minky/project/project2", &statbuf) < 0 ){
            fprintf(stderr, "stat error\n");
            printf("%s\n",strerror(errno));
            exit(1);
        }

它工作正常并且不返回错误(“没有这样的文件或目录”)。

标签: clinuxubuntu-18.04string-literalsstat

解决方案


推荐阅读