RicardasSim

preventing an accidential overwrite

Aug 11th, 2019
677
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <ctype.h>
  6.  
  7. int main()
  8. {
  9.  
  10.     FILE *fp;
  11.     char fileName[] = "test_text_file.txt";
  12.  
  13.     fp = fopen(fileName, "r");
  14.  
  15.     if (fp)
  16.     {
  17.         printf("WARNING: file \"%s\" already exists ! Overwrite it ? [Y/N]\n", fileName);
  18.  
  19.         char c = toupper(getchar());
  20.  
  21.         if ( c != 'Y' )
  22.         {
  23.             printf("Not overwriting. Bye !\n");
  24.             fclose(fp);
  25.             return 0;
  26.         }
  27.  
  28.         fclose(fp);
  29.  
  30.     }
  31.  
  32.     fp = fopen(fileName, "w");
  33.  
  34.     if (!fp)
  35.     {
  36.         printf("ERROR: can't open file \"%s\" for writing !\n", fileName);
  37.         return -1;
  38.     }    
  39.  
  40.     fprintf(fp,"%s\n", "some text");
  41.  
  42.     fclose(fp);
  43.  
  44.     printf("INFO: a \"%s\" file has been written (overwritten). Bye !\n", fileName);
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment