简体   繁体   中英

How to check whether a the program has created a file in the past

So, I have created a program that creates a separate file for every individual student to store his data. I have set a bool variable to restrict accessing data without entring it but it only allows me to get data if I stored it first while I run the program but I restart the program multiple times which means it won't let me get data if I entered it in the previous run as it thinks that I never entered the data. So I want to add a simple (strictly) function/check that checks whether a file was created in the past (in the previous run) or not if yes then it should let me access that data and (if possible) tell me the name of the file so that I can easily access it and if not then it should give me the default error that I coded.

    if (first_entry == false)
    {
        cout << "Enter data first.\n";
        system("pause");
        goto main;
    }

Also, I am using switch statements so in case 1: I ask for data also making >> first_entry = true. In case 2: I have the check that I have mentioned above if true it displays data from the desired file.

Yes, there is a way to check if file exists. You will have to know it's name first, though. I guess that since you have some files already created, then you have your data stored in some sort of array / other structure and based on that you can guess the name of the file.

Anyways, here's the code:

#include <fstream>
...

fstream file;
file.open("directory/your_file.txt", ios::in); //this is where you 
                                               //need to know the filename

if(file.good()) // <-- if file stream returns 'goodbit' iostate
                // which means "does this file open and contain some data"
{
    /* handle data */
}

You can find more about good() here .


Since you already use system() , you can also echo out content of directory using basic windows shell commands, but it seems to be a workaround-like bad solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM