C++ || Snippet – How To Display The Current Working Directory
The following is sample code which demonstrates how to display the current working directory of the program when its properties were initialized.
If you are a system admin, this has a similar effect to the “echo %CD%
” Windows Shell command or the “pwd
” Unix/Linux terminal command, which essentially displays the current working directory the program is located at.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// ============================================================================ // Author: K Perkins // Date: Mar 12, 2013 // Taken From: http://programmingnotes.org/ // File: pwd.cpp // Description: Demonstrates how to display the current working directory // the program is located at to the screen. // ============================================================================ #include <iostream> using namespace std; // determine which platform #ifdef _WIN32 #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif int main() { // declare variables char filePath[256]; // get current directory if(!GetCurrentDir(filePath, sizeof(filePath))) { cout<<"** ERROR - Something went wrong, exiting...n"; } else { cout<<"This file is located in directory:nn"<<filePath<<endl; } cout<<"nPlease press ENTER to continue..."; cin.get(); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Note: This was compiled using a Windows computer
This file is located in directory:
C:UsersAdminDesktop
Please press ENTER to continue...
Leave a Reply