Bonjour,

J'ai quelques soucis en voulant concaténer les 4 lignes d'un fichier texte "test.txt", contenant :
un
deux
trois
quatre
Voici le bout de code :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{    
    FILE *f;
    char ligne[BUFSIZ];
    unsigned char i = 0;
    char **tab = NULL;
    char *str;
 
    // allocation
    tab = malloc(4 * sizeof *tab); // alloue 1 octet par ligne
    if (tab != NULL)
    {
        for (i = 0; i < 4; i++)
      	{
            tab[i] = malloc (10+1 * sizeof *tab[i]); // alloue 10 caractères + 1 caractère NULL
            if (tab[i] == NULL)
            {
      	        for (i = 0; i < 4; i++)
      	     	    free (tab[i]);
      	     	free (tab);
      	     	printf("problème de lors de l'allocation \n");
      	     	exit(EXIT_FAILURE);
            }
      	}
    }
    else 
    {
        free (tab);
    	printf("problème de lors de l'allocation \n");
    	exit(EXIT_FAILURE);
    }
 
    // lecture fichier
    f = fopen("test.txt", "r");
    if(f == NULL)
    	printf("erreur d'ouverture \n");
 
    i = 0;
    while (fgets(ligne, sizeof ligne, f) != NULL)
    {
    	strcpy(tab[i], ligne);
    	printf(tab[i]); // contrôle
    	i++;
    }
    tab[i] = NULL;
 
    // allocation
    str = malloc (2+4+5+6+1 * sizeof *str);
    if (str == NULL) 
    {
        free (str);
    	printf("problème de lors de l'allocation \n");
    	exit(EXIT_FAILURE);
    }
 
    //  concaténation des lignes du tableau
    i = 0;
    while (tab[i] != NULL)
    {
        str = strcat(str, tab[i]);
        i++;
    }
    printf(str); // contrôle
 
    // free() ...
 
    return EXIT_SUCCESS;
}