Search code examples
c++cfunctiongetcwd

Wrap C block in function. Beginner question


I found the C snippet to get the current working directory from here. Essentially, the code is:

char directory[_MAX_PATH];
getcwd(directory, sizeof(directory))

I want to abstract that into another function, in a different file (so it can be swapped out on different platforms if necessary).

Currently, I have in the external file

void getCurrentDirectory(char *directory) {
    getcwd(directory, sizeof(directory));
}

and in the main file

char directory[100];
getCurrentDirectory(directory);
printf("%s", *directory);

However, when printing to screen, I get nonsense (possibly trying to print memory location as a string?)

I'm sure it's something blindingly obvious to a non-beginner. What's going on?

Edit: I'm on Windows 7, btw

Thanks.


Solution

  • Theres a number of things that you are doing wrong here:

    void getCurrentDirectory(char *directory) 
      {
          getcwd(directory, sizeof(directory));
      }
    

    Mistake 1:

    `sizeof(directory)` 
    

    gives you size of a pointer, to be precise, char *. Your intention is to pass size of the array, and not the pointer size.

    Mistake 2:

    `printf("%s", *directory);` 
    

    Passes first element of the array to the printf not the address of the array. Your intention is to print the entire array not just the first element.

    Corrected Solution

    You should be doing

    void getCurrentDirectory(char *directory, size_t arrSize)  
    {                                         ^^^^^^^^^^^^^^
        getcwd(directory, arrSize);
    }
    

    Size of the array is passed explicitly so the function can just use it.

    In the main while printing the contents of the array:

       printf("%s", directory);