对于当前项目,我必须使用mkdir函数创建目录。为了做到这一点,我无法调整示例pwd
代码来生成包含当前目录的文件路径的字符串。
我修改了original example code以接受节点和字符串,并且当它以递归方式遍历文件树时,每一步都写入字符串。然后,当命中基本案例时,字符串将返回到原始函数。
对于长代码段
抱歉//modified from book, need to get entire file path to create new directories
char *printpathto( ino_t this_inode, char* name)
{
ino_t my_inode ;
if ( get_inode("..") == this_inode ) //root points to self
return name;
chdir( ".." ); /* up one dir */
// find this dirs actual name
if (inum_to_name(this_inode,name,BUFSIZ))
{ // 1st: print parent dirs recursively
my_inode = get_inode( "." );
printpathto( my_inode, name);
}
return name;
}
int inum_to_name(ino_t inode_to_find, char *namebuf, int buflen)
{
DIR *dir_ptr; /* the directory */
struct dirent *direntp; /* each entry */
dir_ptr = opendir( "." );
if ( dir_ptr == NULL ){
perror( "." );
exit(1);
}
// search directory for a file with specified inum
while ( ( direntp = readdir( dir_ptr ) ) != NULL )
if ( direntp->d_ino == inode_to_find )
{
strncpy( namebuf, direntp->d_name, buflen);
namebuf[buflen-1] = '\0'; /* just in case */
closedir( dir_ptr );
return 1;
}
strcpy(namebuf, "???"); // couldn't find it
return 0;
}
ino_t get_inode( char *fname )
{
struct stat info;
if ( stat( fname , &info ) == -1 ){
fprintf(stderr, "Cannot stat ");
perror(fname);
exit(1);
}
return info.st_ino;
}
当我通过调试器运行时,当前目录显示在字符串中,但下一次调用是SIGABORT发生并打印回溯时。
首先,我必须修改原始代码以返回字符串而不是将其打印到stdout,但我不确定为什么会发生这种反向转储。
有什么想法吗?
答案 0 :(得分:3)
getcwd()
出了什么问题?
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
}
else {
printf("getcwd() error %i",errno);
}
return 0;
}