PDA

View Full Version : Time in C++



Muscovy
07-13-2009, 07:38 PM
I'm trying to get the time in months and days, but I've only found codes in C to do that.
Actually, the intention of this is to tar a file, and record the month and day somewhere, ideally in the name, but a hidden file would also work.

Here's the program as it is now, no time function.


#include <iostream>
#include <stdlib.h> //For system()

using namespace std;

int main()
{

//Creates a hidden tarball in home.
system("tar -cvvf ~/.Record.tar Record/");

}

If I wanted to make a variable go in the name, would it be done as system("tar -cvvf ~/."<< x <<"Record.tar Record/"); ?

tabstop
07-13-2009, 07:45 PM
C++ appropriated most of the C standard library, and that was part of it. So change <time.h> to <ctime> and off you go.

Notice that system requires a C-string, so you would have to build your command somewhere (a stringstream perhaps) and then convert it (with .str().c_str() or whatever)

Muscovy
07-13-2009, 07:48 PM
I don't quite understand the second part.

tabstop
07-13-2009, 07:55 PM
You want to do system(something) right? That something can't be a std::string, it has to be a C-string. But presumably you want to build it using all the power tools C++ gives you. So:


std::stringstream command;
command << "tar -cvvf ~/.";
command << month << day << "Record.tar Record/";
system(command.str().c_str());

You have to use str to get a string back from your stringstream object, and then use c_str on that to get a C-string you can pass to system.