2

I've got a problem with this simple code :

int main(int argc, char const *argv[]) {
  int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT);

  dup2(fichier, 1);

  printf("test");
  return 0;
}

I just need to write "test" on my file with dup2 and printf. But nothing append to the file.

Thanks if you have a solution

ztarky
  • 53
  • 1
  • 5
  • the posted code fails to compile! amongst other things, it is missing the needed `#include` statements for: ` #include #include #include ` for the `open()` function, `#include ` for the function: `dup2()`. `#include ` for the function: `printf() – user3629249 Apr 20 '18 at 01:29
  • when calling `open()`, always check (0>=) the returned value to assure the operation was successful. when calling `dup2()`, always check the returned value (!= -1) to assure the operation was successful. – user3629249 Apr 20 '18 at 01:32
  • 1
    Possible duplicate of [How to write to a file using open() and printf()?](https://stackoverflow.com/questions/35185503/how-to-write-to-a-file-using-open-and-printf) – Tony Tannous Apr 20 '18 at 01:40
  • suggest using this form of the `open()` statement: `int open(const char *pathname, int flags, mode_t mode);` so the resulting file can be read, etc – user3629249 Apr 20 '18 at 01:44

2 Answers2

3

the following proposed code

  1. cleanly compiles
  2. performs the desired functionality
  3. properly checks for errors
  4. 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
user3629249
  • 16,402
  • 1
  • 16
  • 17
0

Your example does work with the appropriate headers, but it gives the file permissions that only allow the root user to read the file after it has been created by this program. So I added rw permissions for user. I also removed O_APPEND because you said you didn't want to append:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main() {
  int fichier = open("ecrire.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);

  dup2(fichier, 1);

  printf("test");
  return 0;
}
ericcurtin
  • 1,499
  • 17
  • 20