0

I'm using Ubuntu 16.10. I want to copy contents of a file to another file using execlp. I have two files named file1 (with content) and file2 (empty). If I give the following command on terminal

test@ubuntu:~/Teme$ cat file1 > file2

Everything works perfect, but if I write a C code and use this:

execlp("/bin/cat","cat","file1",">","file2",NULL);

I get the error:

content of file1
cat: '>': No such file or directory

I thought that execlp is taking cat arguments one by one so I tried

execlp("/bin/cat","cat","file1 > file2",NULL);

but then I got this error:

cat: 'file1 > file2': No such file or directory

How can I copy the content from a file to another using execlp / execl?

4
  • cat does not copy between files -- that's cp. cat concatenates files to standard output.
    – AlexP
    Nov 30, 2016 at 11:11
  • Looks like you are calling cat as a command and then as the first parameter to itself: execlp("/bin/cat","cat","file1 > file2",NULL); Nov 30, 2016 at 11:13
  • @WinEunuuchs2Unix 0th parameter. $0/argv[0] is usually the name of the command. See unix.stackexchange.com/q/315812/70524
    – muru
    Nov 30, 2016 at 11:16
  • @muru Thanks for C clarification, I've only used exec in Conky and from LibreOffice Calc macros which is different. Nov 30, 2016 at 11:17

1 Answer 1

6

> file2 in cat file1 > file2 are not arguments sent to cat. They're interpreted by the shell (bash, in this case), to redirect the output of cat to file2. You can't do this directly via execlp. What you're doing is the equivalent of cat file1 \> file2 in a terminal, where the >, being escaped, is not interpreted by the shell.

You need to use system(), which uses a shell to execute a command string, or redirect the output using C functions like open() and dup2(). How to do that is a programming question, which belongs on Stack Overflow.

2
  • Yep. Or alternatively they can just open file1 for reading and write contents to file2. Nov 30, 2016 at 14:07
  • 1
    … or you can invoke cp, a program that is actually meant to copy files, and use that in your execlp invocation: execlp("cp", "cp", "file1", "file2", NULL); Nov 30, 2016 at 18:42