#include <iostream>
#include <fstream>
#include <thread>
#include <atomic>
#include <chrono>
constexpr const char* filepath="./1.txt";
int main()
{
using namespace std::chrono_literals;
//очистка файла
{
std::ofstream file(filepath);
}
//поток, пишущий в файл числа
std::atomic<bool> stop{};
std::thread trd([&stop]
{
int n{1};
while(!stop)
{
std::this_thread::sleep_for(500ms);
std::ofstream file(filepath,std::ios::app);
if(file.is_open())
{
file<<n++<<'\n';
file.flush();
}
}
});
//поток, останавливающий процесс записи через 10 секунд
std::thread stop_trd([&stop]
{
std::this_thread::sleep_for(10s);
stop=true;
});
std::ifstream::pos_type last_pos{};
while(!stop)
{
std::this_thread::sleep_for(1000ms);
std::ifstream file(filepath);
if(!file.is_open())continue;
file.seekg(last_pos,std::ios_base::beg);
if(!file)continue;
std::cout<<" opened to read\n";
bool some_read{};
int n{};
while(file>>n)
{
some_read=true;
std::cout<<n<<',';
last_pos=file.tellg();
}
if(some_read)std::cout<<"\n";
}
stop_trd.join();
trd.join();
std::cout<<"done!\n";
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20