【发布时间】:2012-12-07 00:27:55
【问题描述】:
这是我到目前为止的代码,它找到了根的位置,但是当我添加该行时:
printf(" name: %s\n", readdir(opendir(cur_spot))->d_name);
它改变了 cur_spot 并向它添加了奇怪的字符(文件名:.~?)就是它打印的内容。知道为什么会这样吗?
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
struct stat file_stats;
struct stat parent_stats;
struct dirent temp_dir;
char cwd_name[256]; //directory name
char cur_spot[256]; //current directory spot
cur_spot[0] = '.';
stat(cur_spot, &file_stats);
printf("filename: %s\n", cur_spot);
printf(" inode: %ld\n", file_stats.st_ino);
strcat(cur_spot, ".");
stat(cur_spot, &parent_stats);
printf("filename: %s\n", cur_spot);
printf(" inode: %ld\n", parent_stats.st_ino);
while(file_stats.st_ino != parent_stats.st_ino) {
printf("not at root yet\n\n");
stat(cur_spot, &file_stats);
printf(" current child\n");
printf(" inode: %ld\n", file_stats.st_ino);
printf(" name: %s\n", readdir(opendir(cur_spot))->d_name);
strcat(cur_spot, "/..");
stat(cur_spot, &parent_stats);
printf(" current parent\n");
printf(" inode: %ld\n", parent_stats.st_ino);
}
printf("at root\n");
return 0;
}
【问题讨论】:
-
你没有初始化
char cur_spot[256];,所以第一个stat(cur_spot, &file_stats);可以统计谁知道什么。 -
更准确地说,它缺少
cur_spot[1] = 0;。 -
或者用
char cur_spot[256] = ".";初始化它 -
不要忘记为您调用的每个 opendir() 调用 closedir()。你必须保存 opendir() 的返回指针才能做到这一点。
-
我确实有 cur_spot[256] = ".";就像我说的那样,在我添加 open 和 readdir 之前一切正常