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
|
#include <stdio.h>
#include <stdlib.h>
char *lecture_fichier_txt (int ligne)
{
#define TAILLE_MAX 128
char *buf = NULL;
int cpt = 0;
FILE *fichier = fopen ("dico.txt", "r");
if (fichier == NULL) /*debut if fichier */
printf ("ERR : l'ouverture du fichier a echoue\n");
else
{
buf = malloc (sizeof *buf * (TAILLE_MAX + 1)); // Allocation dynamique de memoire
if (buf == NULL) /*debut if buf */
printf ("ERR : Echec d'allocation de memoire");
else
{
while (fgets (buf, TAILLE_MAX + 1, fichier) != NULL) // Boucle peremttant de lire ligne par ligne le fichier
{
/* -ed-
cpt=++cpt;
il faut choisir entre cpt++ et cpt = cpt+1,
mais pas les deux. Comportement indefini...
*/
cpt++;
if (cpt == ligne)
break;
} /*fin while */
if (cpt != ligne)
{
printf ("ERR : ligne %d non trouvee\n", ligne);
free (buf);
buf = NULL;
}
else
{
/* OK : On ne libère pas buf, puisqu'on le retourne */
}
} /* fin if buf */
fclose (fichier);
fichier = NULL;
} /* fin if fichier */
return buf;
}
int main (void)
{
int num_ligne = 7;
char *ligne = lecture_fichier_txt (num_ligne);
if (ligne != NULL)
{
printf ("la chaine est donc : '%s'\n", ligne);
}
return 0;
} |