這是代碼我到目前爲止,找到根源在哪裏是好的,但是當我添加一行:調用執行opendir和readdir的是改變了我的字符數組
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;
}
你不初始化'字符cur_spot [256];',所以第一個'STAT(cur_spot ,&file_stats);'可以統計誰知道什麼。 –
更確切地說,它缺少'cur_spot [1] = 0;'。 –
或用'char cur_spot [256] =「。」;' – Barmar