Jason
Jason

Reputation: 11363

Help figuring out to make a file path string

For the current project, I have to create directories using the mkdir function. In order to do that, I'm having trouble adapting an example pwd code to produce a string containing the file path to the current directory.

I modified the original example code to take in both the node and a string, and as it recursively traverses up the file tree, each step is written to the string. Then when the base case is hit, the string is returned to the original function.

Sorry for the long code snippet

//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;
}

When I run it through the debugger, the current directory is displayed in the string, but the next call is when the SIGABORT occurs and the backtrace is printed.

First, I had to modify the original code to return a string rather than print it to stdout, but I'm not sure why this backtrace dump is occuring.

Any ideas?

Upvotes: 1

Views: 209

Answers (1)

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

What's wrong with 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;
    }

Upvotes: 3

Related Questions