Domanda

I've created this function to print file content :

void afficher (char * nomFichier){
    if( nomFichier == NULL )
       printf("Erreur : %s\n",nomFichier);
    else
     {
       char buf[15];
       int nb;
       int fd = open(nomFichier,O_RDONLY);
       if(fd == -1) printf ("Erreur ouverture : %s\n",nomFichier);
       else
       {
          printf("Fichier : %s\n",nomFichier);//print the file name
          while((nb = read(fd,buf,15)) > 0){
             write(1,buf,nb);
          }
          printf("\n");
          close(fd);
        }
    }
}

The problem is that when I call this function in program that has dup2'ed stdout to a file (fichierSortie in this cas)

int fd = open(fichierSortie, mode, 0666 );
if( fd == -1 ) // erreur 
  Erreur("Erreur lors de création du fichier : ",2);
printf("%d\n",dup2(fd,1)); // on redirige la sortie standard 
close(fd);
afficher(filename);

I got this :

line1
line2
last line of the file
Fichier : filename

but normally I should get

Fichier : filename
line1
line2
last line of the file

Thanks

È stato utile?

Soluzione

Not too sure about this but ...

 // Performed buffered so it goes out when internal buffering is full or flushed
 printf("Fichier : %s\n",nomFichier);
 ...
 // Performed unbuffered, so it goes out promptly
 write(1,buf,nb);

To synchronism, fflush(stdout).

 // Performed buffered so it goes out when internal buffering is full or flushed
 printf("Fichier : %s\n",nomFichier);
 fflush(stdout);
 ...
 // Performed unbuffered, so it goes out promptly
 write(1,buf,nb);
 ...
 printf("\n");
 fflush(stdout);

BTW: Recommend to not attempt to print a NULL.

if( nomFichier == NULL )
   // printf("Erreur : %s\n",nomFichier);
   printf("Erreur : (NULL)\n");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top