Thread: Checking that a file doesn't exist already

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    207

    Question Checking that a file doesn't exist already

    I have a function that saves some values in a file, and the user writes the name of the file, but how would I check if the file already exist? Is there any function that alerts the user about this?

    This is the save function I use:


    ////////////////////////////////////////////////////////

    void
    save_project(void)
    {

    char file_name[8];
    FILE *outp;

    printf("Enter name of file in which to place results: ");
    scanf("%s", file_name);
    outp = fopen(file_name, "w");

    fprintf(outp, "%.2f\n", LOA);
    fprintf(outp, "%.2f\n", I);
    fprintf(outp, "%.2f\n", J);
    fprintf(outp, "%.2f\n", P);
    fprintf(outp, "%.2f\n", E);
    fprintf(outp, "%.2f\n", D);
    fprintf(outp, "%.2f\n", GM);
    fprintf(outp, "%.2f\n", H1);
    fprintf(outp, "%.2f\n", H2);
    fprintf(outp, "%.2f\n", H3);
    fprintf(outp, "%.2f\n", S1);
    fprintf(outp, "%.2f\n", S2);
    fprintf(outp, "%.2f\n", S3);

    fclose(outp);

    printf("\n\nPress any key to continue");
    getch();
    project();

    }


    ////////////////////////////////////////////////////////

  2. #2
    Registered User pinko_liberal's Avatar
    Join Date
    Oct 2001
    Posts
    284
    I dont think there is 100% foolproof way in ansi-c , but you could try some thing like

    int fexists(char *fname)
    {
    FILE *fp;
    fp=fopen(fname,"r");
    if(fp==NULL) return 0;
    else fclose(fp);
    return 1;
    }

    but there are many cases where this might not work .

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    207
    Thanks Pinko, I'll try later.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  4. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM