In the linux terminal, I can type
echo hello! > /path/to/file
I thought I would be able to do the same thing using execv:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(void){
char *write_cmd[] = { "echo", "hello!", ">", "/path/to/file", NULL};
if (fork() == 0){
execv("/bin/echo", write_cmd);
}
else{
sleep(1);
}
return 0;
}
However, this code doesn't write 'hello!' to the file, which is what I want it to do. Is there another way to do this using execv and echo?
Edit: I've tried using dup2 as a solution as well: #include #include #include
int main(void){
char *write_cmd[] = { "echo", "hello!", NULL };
if (fork() == 0){
int tmpFd = open("/path/to/file", O_WRONLY);
dup2(tmpFd, 1);
execv("/bin/echo", write_cmd);
close(tmpFd);
exit(0);
}
else{
sleep(1);
}
return 0;
}
However, this doesn't give me the result I want either. This writes 'hello!' to the file, but it also overwrites everything else that was already written on the file. How can I guarantee that 'hello!' will be written to the END of the file?