c - 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);
}
它工作正常并且不返回错误(“没有这样的文件或目录”)。
解决方案
推荐阅读
- atlassian-sourcetree - SourceTree,查看已删除文件的历史记录。不知道什么时候编辑的
- python - 文件和 str ( \n \n\r ) 的不同编码 - 已解决
- scala - 什么时候逆变有用?为什么使用协方差与继承?
- asp.net-mvc - 为什么 IIS 会针对 403 错误显示它自己的错误消息,而不是依赖于我的 customErrors 元素?
- python - AttributeError:“应用程序”对象没有属性“create_widgets”
- python - 如何在 Python 中的分类器中显示预测的置信度(Tensorflow 2.2/Keras)
- tensorflow - tensorflow 2.x 分布式集群
- android-room - 如何在 WorkManager 中获取 Room Database ViewModel 实例?
- javascript - 使用连字符格式化 yaml 数据以写入文件打字稿
- sql-server - 如何在 Access VBA 中捕获缺少访问错误代码的特定 SQL Server 错误?