简体   繁体   English

如何检查程序过去是否创建了文件

[英]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.我设置了一个 bool 变量来限制访问数据而不输入数据,但它只允许我在运行程序时先存储数据时获取数据,但我多次重新启动程序,这意味着如果我不输入数据,它不会让我获取数据在上次运行中输入它,因为它认为我从未输入过数据。 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.另外,我正在使用 switch 语句,所以在情况 1 中:我要求数据也使 >> first_entry = true。 In case 2: I have the check that I have mentioned above if true it displays data from the desired file.在情况 2 中:我进行了上面提到的检查,如果为 true,它会显示来自所需文件的数据。

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 .您可以在此处找到有关good()更多信息。


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.由于您已经使用了system() ,您还可以使用基本的 windows shell 命令回显目录的内容,但这似乎是一种类似于变通方法的糟糕解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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