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
   |  
#include <stdio.h>
#include <errno.h>
#include <string.h>
 
void openFile(FILE *file,char *mod) //pour ouvrir un fichier avec le mode indique
{
   char path[101];
   errno=0;
   printf("the Path: ");
   fgets(path,101,stdin);
   file=fopen(path,mod);
   if(file==NULL)
   {
      fprintf(stderr,"Error while opening the file\n");
      strerror(errno);
   }
}
 
void writeFile(FILE *file) //pour l'ecriture dans un fichier
{
   char c1=' ',c2;
   if(file==NULL)
   {
      fprintf(stderr,"Error while opening the file %s\n",strerror(errno));
      return;
   }
   printf("press twice enter to quit\n");
   do
   {
      c2=c1;
      c1=getchar();
      fputc(c1,file);
   }while(c1!='\n' && c2!='\n' );
}
 
void readFile(FILE *file) //pour la lecture d'un fichier
{
   char c;
   if(file==NULL)
   {
      fprintf(stderr,"Error while opening the file %s\n",strerror(errno));
      return;
   }
   while(c!=EOF)
   {
      c=fgetc(file);
      putchar(c);
   }
}
 
void closeFile(FILE *file) //pour fermer le fichier
{
   if(file==NULL)
   {
      fprintf(stderr,"Error while opening the file %s\n",strerror(errno));
   }
   else
   {
      fclose(file);
   }
}
int main(void)
{
   char choice;
   FILE *file;
   do
   {
      printf("1-write 2-add 3-read 4-quit:  ");
      choice=getchar();
      switch(choice)
      {
         case '1':{
            openFile(file,"w");
            writeFile(file);
            closeFile(file);
         }
         break;
         case '2':{
            openFile(file,"a");
            writeFile(file);
            closeFile(file);
         }
         break;
         case '3':{
            openFile(file,"r");
            readFile(file);
            closeFile(file);
         }
         break;
         case '4':{
         }
         break;
         default :fprintf(stderr,"invalid choice\n");
      }
      fflush(stdin);//pour vider le buffer
   }while(1);
} | 
Partager