0

I am trying to run the

echo "Hello world" > foo.txt

using execvp.

So far, I have this:

#include <unistd.h>

int main(void) {
  char *execArgs[] = { "echo", "Hello, World! > foo.txt", NULL };
  execvp("echo", execArgs);
  return 0;
}

which will print out the line "Hello, World! > foo.txt", instead of creating a file named foo.txt with the text "Hello, World!" inside.

Someone does something similar on Stack overflow, they does this:

execlp( "/bin/sh", "/bin/sh", "-c", "cat file1.txt > redirected.txt", (char *)NULL );

But when I changed it to

execlp( "echo", "echo", "echo Hello World > redirected.txt", (char *)NULL );

nothing happens.

EDIT:

Doing this worked (Thanks, SometimesRight!)

execlp( "/bin/sh", "/bin/sh", "-c", "echo Hello, World! > redirected.txt", (char *)NULL );
Community
  • 1
  • 1
ndb
  • 127
  • 1
  • 10

1 Answers1

1

execlp runs an executable that it expects to find in the PATH. However echo is not an executable, it is a command that runs in the context of a shell command interpreter such as sh or bash.

I take it back: in Linux there is an echo executable in /bin. However to pipe it to stdout using '>' you need the assistance of a shell like 'sh'.

JonP
  • 627
  • 6
  • 13
  • So does that mean there is no way to use either execlp or execvp to create a file? – ndb Jan 24 '16 at 22:45
  • Yes, by running a shell with the -c argument as given by the other answer you found. Or, use the C library functions fopen(), fputs() and fclose() to write the file directly from your program. If you need more help to use the functions do ask, but the manual pages should tell you all you need. – JonP Jan 24 '16 at 22:49
  • I am assuming you are running Linux - you don't say - if this is Windows you need to use the cmd.exe command interpreter. – JonP Jan 24 '16 at 22:56