the following proposed code
- cleanly compiles
- performs the desired functionality
- properly checks for errors
- contains the
#include
statements needed.
and now the proposed code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT, 0777);
if( 0 > fichier )
{
perror( "open failed" );
exit( EXIT_FAILURE );
}
// IMPLIED else, open successful
if( dup2(fichier, 1) == -1 )
{
perror( "dup3 failed" );
exit( EXIT_FAILURE );
}
// implied else, dup2 successful
printf("test");
return 0;
}
on linux this command:
ls -al ecrire.txt displays
-rwxrwxr-x 1 rkwill rkwill 4 Apr 19 18:46 ecrire.txt
this to browse the contents of the file:
less ecrire.txt
results in:
test