how can I copy a file with full path and rename it in C program using execl? can I use this instruction:
execl("/bin/cat","cat",path_source,">",path_destination,NULL);
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityhow can I copy a file with full path and rename it in C program using execl? can I use this instruction:
execl("/bin/cat","cat",path_source,">",path_destination,NULL);
The code you posted looks like it's intended to mimic the following shell command:
cat path_source >path_destination
But, in that scenario, >
isn't a parameter to cat
; instead, it's
interpreted by your shell, which will run cat
with a single
parameter path_source
, and its standard output connected to
path_destination
. (So your C code really does
cat path_source '>' path_destination
.)
One way to imitate what the cat
command above does is to construct a
string containing your shell command ("cat ... >..."
), and then pass
that, using exec, as an argument to /bin/sh -c
, but it's hard to
make it reliable and safe if you don't know for sure that the file
names verify some constraints.
If you are going to simply rename a file, it might be best to use
standard function rename
from stdio.h
instead. If not, please
clarify your question.
This sounds like a homework assignment, so I'm being intentionally vague.
It sounds like the requirement is to mimic the behavior of the shell when using the output redirection operator. You'd need to manipulate the standard file descriptors before calling execl()
such that standard output of the calling process was an open file descriptor for the target output file. That way when cat writes to standard output, the content will go to the target file.