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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <stdio.h>
#include <stdlib.h>
#define verif_ptr(ope) { if(!(ope)) { printf("\n ----- Erreur d'allocation de la mémoire ----- \n"); exit(1); } }
/* Declarations des fonctions */
char* lecture_clavier(unsigned long);
/* Definition des fonctions */
char* lecture_clavier(unsigned long taille_buffer)
{
int c;
unsigned long i = 0, j = 1;
char *texte = NULL;
if(taille_buffer < 1)
taille_buffer = 5;
texte = malloc(sizeof(*texte)*taille_buffer);
verif_ptr(texte != NULL);
while((c=getchar()) != '\n' && c != EOF)
{
texte[i] = c;
i++;
if(i%taille_buffer == 0)
{
char *tmp = realloc(texte, sizeof(*texte)*taille_buffer*++j);
if(tmp != NULL)
{
texte = tmp;
}
else
{
free(texte);
return NULL;
}
}
}
if(c == EOF)
{
free(texte), texte = NULL;
}
else
{
texte[i] = '\0';
if(i == 0 || (i+1)%taille_buffer != 0)
{
char *tmp = realloc(texte, sizeof(*texte)*(i+1));
if(tmp != NULL)
texte = tmp;
}
}
return texte;
}
/*************************************/
/* Programme principal */
/*************************************/
int main(int argc, char** argv)
{
/* Exemple 1 : lire au clavier */
printf("\n----- Exemple 1 : lire au clavier -----\n\n");
char *machaine = NULL;
printf("Entrez une chaine de caracteres :\n");
machaine = lecture_clavier(0);
printf("\n\nLa chaine tapee est :\n%s\n\n", machaine);
free(machaine);
/* Exemple 2 : lire un fichier ligne par ligne*/
printf("\n----- Exemple 2 : lire un fichier ligne par ligne -----\n\n");
FILE *monfichier = freopen("lecture_clavier.c", "r", stdin);
if(monfichier != NULL)
{
char *ligne;
unsigned short i = 1;
while((ligne = lecture_clavier(15)) != NULL)
{
printf ("Ligne %d = '%s'\n", i, ligne);
free(ligne);
i++;
}
}
fclose(monfichier);
return 0;
} |