1

I am trying to print the path of the current directory using this execl ("/bin/pwd", "pwd", NULL); output: /home/user/Ubuntu and want to print a desired text before the current path. for example: my name /home/user/ubntu

how this will be done?

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <dirent.h>

using namespace std;
int main(){
    string command;
    while(command != "exit"){
    cout<< "B-17235"<<return execl ("/bin/pwd", "pwd", NULL);
    cin>> command;
}

return 0;
}
Waqas Adil
  • 260
  • 1
  • 12

2 Answers2

3

Think that the majority of Unix-Linux-Gnu commands are written in C or C++. Generally there are direct API calls either system calls (man 2) or standard C library (man 3) to get the information or do the job.

To get working directory, just use getcwd() as suggested by alk.

char buffer[256];
if (NULL == getcwd(buffer, sizeof(buffer))) {
    perror("can't get current dir");
    return 1;
}

If you wanted to get the output of a more complex command, the most direct way would be to use popen that encloses the fork, exec, and pipe management for you :

FILE *fd = popen("/bin/pwd", "r");
char buffer[256];

if (fgets(buffer, sizeof(buffer), fd) == NULL) {
    perror("can't read command");
    return 1;
}
if (buffer[strlen(buffer) - 1] != '\n') {
    fprintf(stderr, "path too long";
    return 1;
}
pclose(fd);
// ok the working directory is is buffer

You should not use that for a command as simple as pwd.

And don't forget : man is your friend ! man getcwd and man popen will give you plenty of information ...

Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199
  • 2
    You say you are a beginner. You must practice. alk and I gave you enough elements. Try to make a running code. If it runs but you want to know if you could have written it better, ask in [code review](http://codereview.stackexchange.com/). If it's broken and you can't fix it alone, ask here. But ... **you** must pratice :-) – Serge Ballesta Nov 03 '14 at 16:31
1

I am trying to print the path of the current directory

Use the library function getcwd().

To have the function available it might be necessary to #define _XOPEN_SOURCE 500 or similar (please see the man-page linked above for details on this).

alk
  • 66,653
  • 10
  • 83
  • 219
  • @WaqasAdil: Using `getcwd()` is also possible in C++. – alk Nov 03 '14 at 16:15
  • @WaqasAdil: You might like to have a look here: http://stackoverflow.com/q/2203159/694576 (this took my 3sec to gxxgle, btw :-/) – alk Nov 03 '14 at 16:48