【发布时间】:2016-03-14 23:21:22
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char** argv) {
struct stat *buf;
buf = malloc(sizeof(struct stat));
DIR * current_directory_ptr; /* DIR is a type from dirent.h */
struct dirent * next_entry_ptr; /* struct dirent is a type from dirent.h */
char* dirToView [200];
printf("Enter path of desired directory\n");
scanf("%s)", &dirToView);
current_directory_ptr = opendir(dirToView);
next_entry_ptr = readdir (current_directory_ptr);
while(next_entry_ptr != NULL){
printf("File has inode number %d and is called %s \n",
(int) next_entry_ptr ->d_ino, next_entry_ptr->d_name);
next_entry_ptr=readdir(current_directory_ptr);
}
char* fileToView [200];
printf("Enter name of desired file\n");
scanf("%s)", &fileToView);
stat(fileToView, buf);
off_t size = buf -> st_size;
printf("Size = %ld \n", size);
uid_t owner = buf ->st_uid;
printf("owner = %d \n", owner);
closedir(current_directory_ptr);
return (EXIT_SUCCESS);
}
此代码的目的是使用扫描来获取和输出所选文件的详细信息。打开一个目录是可行的,但是在打开一个文件时,大小和所有者的结果都是 0,而不管该文件的实际值如何。我相信这样做的原因是我将它们打印为错误的类型,但我不确定这一点。输出 stat() 结果的正确系统是什么?
为清晰起见进行编辑
问题在于下面突出显示的行
char* fileToView [200]; printf("Enter name of desired file\n"); scanf("%s)", &fileToView); stat(fileToView, buf); off_t size = buf -> st_size; printf("Size = %ld \n", size); uid_t owner = buf ->st_uid; printf("owner = %d \n", owner);
程序中较早的代码按预期运行,至少有一个响应引用了较早的行。对于任何缺乏明确性,我深表歉意。
【问题讨论】:
-
不要使用
scanf("%s)", &dirToView);和scanf("%s)", &fileToView);,它们会导致类型不匹配和未定义的行为。 -
在这种情况下正确的类型是什么?有目录类型吗?
-
使用
char dirToView [200]; scanf("%199s)", dirToView);和char fileToView [200]; scanf("%s)", fileToView);