c executing shell problem

Hello
im geting error here:

#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main (int argc, char *argv[])
{
char user[20];
string command;
 cin << user;
command = printf ("grep '%s' /etc/shadow", user);

system (command.c_str());
 }
 return 0;
}

it should search shadow file for a entered user, but it shows "sh not found"

to start off:

printf ("grep '%s' /etc/shadow", user);

Is not a valid command in sh or bash.

What system does -

  1. fork a new process
  2. exec a shell in the child process and pass the arguments to to it
  3. wait until the child process is done
  4. get status from wait (see man 2 wait nad man system for exact details)

When you are at the command line:
show the output of

ls /bin/sh

What does your system manpage say about the default name of the shell it intends to use? -- it may refer you to exec...

#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main (int argc, char *argv[])
{
char user[20];
string command;
 cin << user;
command = printf ("grep '%s' /etc/shadow", user);

system (command.c_str());
 }
 return 0;
}

I'm surprised this even compiles. How did you get namespace::std or cin without iostream?

also, printf doesn't work that way. printf prints to stdout. If you want to print to a string, you use sprintf, like this:

char buf[512];
sprintf(buf, "grep '%s' /etc/shadow", user);

---------- Post updated at 12:49 PM ---------- Previous update was at 12:48 PM ----------

Lastly, why write a C command to run a shell command? wouldn't it be easier to run the shell command in the first place?

Why not do it all from within C using the getpwent() et al APIs? Much safer.

hi..
why dont you use exec family of functions to execute shell scripts from within the C program.
you can use execlp.
plz check the exec family of functions. its the most portable and simple way of executing shell commands. plz reply to extend this conversation. :slight_smile:
regards
ttyl

#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main (int argc, char *argv[])
{
char user[20];
string command; ---> char command[25];
cin << user; ----> cin>>user;
command = printf ("grep '%s' /etc/shadow", user); --->

sprintf(command,"grep '%s' /etc/shadow", user)

system (command.c_str());

return 0;
}

Try this..

Please use

code tags 

Why to mix printf with cin, just use scanf instead of cin?