-1

Usually when the file name is "example.txt", I can use the following code to read from the file.

string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

But how can I use the same program to read a file, When the file name is example_201703031140.txt or example_201703031142.txt. (Let's just say this file is the only file in the location with that prefix. In other words, the location can have either example_201703031140.txt OR example_201703031142.txt, not the both )

To clarify the question more, how can I write a program to which can read dynamically changing file names? For example imagine a scenario that I have to write to file which is named example_timestamp and read that file from a separate module (which do not have access to the full file name, but knows that it has a prefix "example" followed by a timestamp)

Update: You do not know what the timestamp is, you just know that it is a timestamp.

SanD
  • 503
  • 2
  • 7
  • 25
  • X-Y option. If the file writes are spaced out enough that they won't overlap a read, always write the same name.Then read the common name and rename the file with the timestamp when done. – user4581301 Mar 03 '17 at 06:26
  • otherwise get a directory listing (os specific code or the likes of Boost required for the next few months until C++17 drops) and pic to the file want from the list. – user4581301 Mar 03 '17 at 06:27
  • Another X-Y option: open an IPC Connection like a socket or pipe between the two processes and have the writer tell the reader when there is a file available and what the name is. – user4581301 Mar 03 '17 at 06:38

2 Answers2

1

I guess you would like something like this:

DIR* dirp = opendir("the dir name");
while(struct dirent* e = readdir(dirp)){
     if e->d_name matches the pattern you wanted{
           do whatever you want with this file.
     }
}
qianfg
  • 878
  • 5
  • 8
-2

First, you need to create the prefix or postfix of the file name, for example creating a date time format:

char buffer[128];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, format.c_str(), timeinfo);
out << buffer;

After that you build the file name to validate and use it.

In the link link a show you how i create a library to create logs with dynamic names and reuse them:

https://github.com/jorgemedra/APILogCpp/blob/master/APILogCpp/UIPILog/LogManager.cpp

Jorge Omar Medra
  • 978
  • 1
  • 9
  • 19