how can i make a loop to read file until it's found.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<bits/stdc++.h>

using namespace std;
int main()
{
ifstream in("test2.txt");
while(!in.is_open())
{
	in.close();
	ifstream in("test2.txt");
	cout<< "not"<<endl;
	_sleep(2000);
}
 cout<<" in ";
}


at first there is no test2.txt then i created it while running the program.
expected output: "in".
but i got loop of " not ".
ifstream just opens a file for input if it exists. To create file you need to open for output. Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
	ifstream in;

	for (; in.open("test2.txt"), !in.is_open(); _sleep(2000))
	{
		ofstream of("test2.txt");
		cout << "not" << endl;
	}

	cout << " in ";
}

Last edited on
Hello Brjdyxter,

You wrote:
how can i make a loop to read file until it's found.

A little confused here. Does this mean to read from a file until something is found? Or to do something with a file name(s) until you get 1 to open?

Going over your code this is what I see:
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
//#include<bits/stdc++.h>  // <--- I do not have this file and you should not be using it either.
#include <iostream>
#include <Windows.h>
#include <fstream>

using namespace std;

int main()
{
    ifstream in("test2.txt");  // <--- Defines stream variable and opens file for input.

    while (!in.is_open())  // <--- Checks if not open. Could be simpley written as "(!in)". Does the same, but can catch more errors.
    {
        in.close();

        ifstream in("test2.txt");  // <--- Defines stream variable and opens file for input, but in the scope of the while loop. This is different from the first "ifstream".
        //  Use "ofstream" if your intent is to create the file.

        cout << "not" << endl;  // <--- Since the while condition will always be true. This prints an endless loop to the screen.

        //_sleep(2000);  // <--- May not be available to everyone. The newer version is "Sleep()" in the <windows.h> file.
        //Sleep(2000);
    }

    cout << " in ";  // <--- Never reached because of the while loop.

    return 0;  // <--- Not required, but makes a good break point.
}

Some things to consider.

I do like what seeplus did.

Andy
There is no test2.txt file when i run the program.
The program will make a loop to reload after 2 sec to check if the file exist then read it. I will add the test2.txt later.
If the file is exist, the program will do the next code.
Topic archived. No new replies allowed.