ztarky
ztarky

Reputation: 53

trouble to write in a file with dup2 and printf

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

Upvotes: 2

Views: 995

Answers (2)

user3629249
user3629249

Reputation: 16540

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

Upvotes: 3

ericcurtin
ericcurtin

Reputation: 1717

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;
}

Upvotes: 0

Related Questions