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 100 101 102 103 104 105 106 107 108 109
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAILLE_MAX 1000
char nf[80];
FILE* fichier = NULL;
void readFile(char nf[80]);
void writeFile(char nf[80]);
int entree(char *chaine, int longueur);
int main(){
int choix = 0;
printf(" MENU \n");
printf("1. Lire un fichier\n");
printf("2. Creer un fichier\n");
printf("3. Ecrire dans un fichier\n");
printf("Votre choix ?");
choix = fgetc(stdin);
while(fgetc(stdin)!='\n') ;
if (choix == '1') {
printf("Nom du fichier a lire :\n");
fflush(stdin);
entree(nf, 80); }
else if(choix == '2') {
printf("Nom du fichier a creer :\n");
fflush(stdin);
entree(nf, 80);
}
else if(choix == '3') {
printf("Nom du fichier a ecrire :\n");
fflush(stdin);
entree(nf, 80);
}
else {
printf("Veuillez entrer un nombre valide !\n"); }
printf("\n");
switch(choix) {
case '1':
readFile(nf);
break;
case '2':
//createFile(nf);
break;
case '3':
writeFile(nf);
break;
}
return 0;
}
void readFile(char nf[80]) {
fichier = fopen(nf, "r");
int caractereActuel = 0;
if(fichier == NULL) {
printf("Impossible d'ouvrir le fichier");
exit(1);
}
printf(".............. Ouverture du fichier %s\n", nf);
caractereActuel = fgetc(fichier);
while (caractereActuel != EOF) {
printf("%c", caractereActuel);
caractereActuel = fgetc(fichier);
}
fclose(fichier);
getchar();
}
void writeFile(char nf[80]) {
char entree[100];
fichier = fopen(nf, "w");
if(fichier == NULL) {
printf("Ce fichier n'existe pas, il sera cree.\n");
}
printf("Que voulez-vous ecrire dans ce fichier ?\n");
fgets(entree, 80, stdin);
fputs(entree, fichier);
fclose(fichier);
}
int entree(char *chaine, int longueur)
{
char *Entree = NULL;
if (fgets(chaine, longueur, stdin) != NULL){ // Si la saisie se fait sans erreur
Entree = strchr(chaine, '\n');
if (Entree != NULL) // Si on a trouvé le retour à la ligne
{
*Entree = '\0'; // On remplace ce caractère par \0
}
return 1;
}
else {
return 0;
}
} |
Partager