This is the code i have so far, it finds where the root is fine, but when i add the line:
printf(" name: %s\n", readdir(opendir(cur_spot))->d_name);
it changes cur_spot and adds weird characters to it (filename: .~?) is what it prints.. any idea why this is happening?
#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;
}
This works fine for me on GCC:
#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;
DIR *dirp;
char cwd_name[256]; //directory name
char cur_spot[256]; //current directory spot
strcpy(cur_spot,"."); // <------------ changed
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);
dirp=opendir(cur_spot); // <----------------added
printf(" name: %s\n", readdir(dirp)->d_name); // <----changed
closedir(dirp); // <------------------------added
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;
}