0

Recently I've been asked to write a C program combining every line of a file with all lines of another file. So typically I use "%s%s" but the second %s goes on the next line, but I want it to be all on the same line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TAILLE_LIGNE 100

int main(int argc, char* argv[]) {
  FILE* fichier1 = fopen(argv[1], "r");
  FILE* fichier2 = fopen(argv[2], "r");
  FILE* fichier3 = fopen("newfile.txt", "w");

  if(!fichier1 || !fichier2 || !fichier3) {
    fprintf(stderr, "Pas possible de lire les fichiers");
    exit (0);
  }

  char* ligne1 = (char*)calloc(MAX_TAILLE_LIGNE, sizeof(char));
  char* ligne2 = (char*)calloc(MAX_TAILLE_LIGNE, sizeof(char));

  if(!ligne1 || !ligne2) {fprintf(stderr, "Pas possible d'allouer une chaine de caracteres"); exit(0);}

  while(fgets(ligne1, MAX_TAILLE_LIGNE, fichier1) != NULL) {
    rewind(fichier2);
    while(fgets(ligne2, MAX_TAILLE_LIGNE, fichier2) != NULL) {
      fprintf(fichier3, "%d%s%s", 1, ligne1, ligne2);
    }
  }
  free(ligne1);
  free(ligne2);
  fclose(fichier1);
  fclose(fichier2);
  fclose(fichier3);
  return 0;

}

So, for example, given file number 1 :

As\n
Roi\n
Dame\n
Valet\n

And the second file :

Coeur\n
Carreau\n
Pique\n

I want the result to be something like this :

1AsCoeur
1AsCarreux
1AsPique
1RoiCoeur
1RoiCarreux
1RoiPique
1DameCoeur
1DameCarreux
1DamePique
1ValetCoeur
1ValetCarreux
1ValetPique

But instead, I have this :

1As
Coeur
1As
Carreux
1As
Pique
1Roi
Coeur
1Roi
Carreux
1Roi
Pique
1Dame
Coeur
1Dame
Carreux
1Dame
Pique
1Valet
Coeur
1Valet
Carreux
1Valet
Pique

I tried several ways to concatenate strings but no matter how hard I'm trying, I have the same result.

user3386109
  • 34,287
  • 7
  • 49
  • 68
Amir_pn
  • 1
  • 1

0 Answers0