How do I create a filepath with today's date?

Today is April 1, 2010.  I want to create a filepath "C:\2010\4\1\Example.txt" from today's date.  How do I do this?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It really depends on what form you know that today is April 1, 2010.
Are the pieces of information in the form "April", "1", and "2010"; or in some other form, such as integers of 4, 1, 2010, respectively; or in some other form. Please advise.
shaolinfunkAuthor Commented:
I don't know where to get the date from. How does the computer know that today is April 1, 2010?

Isn't there a way for C++ to get the computer's internal time and date?  And from that can we create a string that becomes a file path?
shaolinfunkAuthor Commented:
Your questions forces me to clarify my question and make them more concise.

With C++ how do I obtain today's date from the computer's internal clock, and create a string with the obtained date?
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Looks like we need to use pointers since the built-in library functions require them. But you won't need to worry too much (unless things go wrong) since these functions are used in a standard pattern. There possibly may be some locale issues, but we'll see.

For starters, you should become familiar with the time.h available functions:
and become familiar with the time_t data type:
     -- Notice here that the expression "the number of seconds elapsed
        since 00:00 hours, Jan 1, 1970 UTC"
    -- "In casual use, when fractions of a second are not important, Greenwich Mean Time (GMT) can be considered equivalent to UTC "
        ---- Ref:
             -- I think we are casual, so the number of seconds is a GMT number of seconds
                which is not your local time.

and definitely look at:
which returns the number of seconds since January 1, 1970 (like the Y2K problem, we now have a Y2038 problem)

Take a look and see if you have any questions on the above links. We need to convert the seconds to a form suitable for your folder name convention. I'll provide a post with suggestions on that shortly.
shaolinfunkAuthor Commented:
I am completely lost.  Those links are confusing and I don't see how I can obtain today's date and make a string / filepath out of it.
Sorry about that being lost. This stuff is pretty tricky and probably not suitable for a beginner. But I don't see how to avoid struct and pointers to do what you are asking. Once you get that knowledge, you will find it easier. I tried to find something without these two concepts but was unsuccessful.

I believe that after using the time function, you need to use the localtime function. There is source code here that I am posting with one small modification related to the year (I changed a y to a Y).

This is just one step closer to your final goal.

Test this please. Ask questions. Accept on faith??

/* localtime example */
#include <time.h>
#include <stdio.h>

int main()
    time_t rawtime;
    struct tm * timeinfo;
    char str[60];

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    strftime(str, sizeof(str) , "%d%b%Y", timeinfo);
    printf(str);    // date

    //strftime(str, sizeof(str) , "%H%M%S", timeinfo);
    //printf(str);    // time

    return 0;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
shaolinfunkAuthor Commented:
it compiles successfully...but there are warnings that i don't understand:
1>------ Rebuild All started: Project: junk, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'junk', configuration 'Debug|Win32'
1>c:\documents and settings\administrator\desktop\junk\junk\junk.cpp(65) : warning C4996: 'localtime' was declared deprecated
1>        c:\program files (x86)\microsoft visual studio 8\vc\include\time.inl(114) : see declaration of 'localtime'
1>        Message: 'This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'
1>Compiling manifest to resources...
1>LINK : C:\Documents and Settings\Administrator\Desktop\junk\Debug\junk.exe not found or not built by the last incremental link; performing full link
1>Embedding manifest...
1>Build log was saved at "file://c:\Documents and Settings\Administrator\Desktop\junk\junk\Debug\BuildLog.htm"
1>junk - 0 error(s), 1 warning(s)
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Open in new window

shaolinfunkAuthor Commented:
even with the warning it successfully prints today's date to the DOS prompt window though.  what's the next step?
Right, you have one warning. It says that 'localtime' is deprecated or may be unsafe (and sometime from now will likely no longer be supported).

For now, accept this warning, and you can suppress it as follows:

Right-click on the project and select Properties
Expand C/C++ and select Preprocessor
Add _CRT_SECURE_NO_WARNINGS to Preprocessor Definitions

Every once in awhile, change _CRT_SECURE_NO_WARNINGS to XX_CRT_SECURE_NO_WARNINGS to remove the macro, find out what is deprecated, and we can find a more acceptable approach.

The unsafe business if often related to multi-threading issues where one thread can clobber some aspect of another thread. time.h has a number of issues in this regards.
shaolinfunkAuthor Commented:
Ok, now the next do we get from your code to a filepath that contains the date?
shaolinfunkAuthor Commented:
ok i will try to deconstruct what you're doing.  correct me if i'm wrong.

Rawtime is a variable of data type time_t.  Data type time_t becomes possible only because we included that time.h file.

Timeinfo points to a struct called "tm"

str is a character array that can hold 61 characters.

time ( &rawtime) retrieves the time? and returns the address of variable rawtime which now holds the time?

what does line 12 & 14 do?  i have no idea.

line 15 prints the character array str to the dos prompt so i can see it...

shaolinfunkAuthor Commented:
btw, are you on East Coast time?  it's almost midnight here and i don't mean to keep you up.  
EDST - southeaster PA
how about you?
shaolinfunkAuthor Commented:
ok, New York EST.
>> Rawtime is a variable of data type time_t.  Data type time_t becomes possible only because we included that time.h file.
yes, and likewise struct tm becomes known also because we included that time.h file.

>> Timeinfo points to a struct called "tm"

str is a character array that can hold 61 characters.
No, str is a character array that can hold 60 characters in the example; however, be advised that if using c-style strings, the string must be terminated by a null byte (i.e., 0, or also known as '\0' to emphasize that it is terminating null byte).

time ( &rawtime) retrieves the time?
yes, but in GMT (aka a time defined at longitude 0 degrees, near London). It is a time defined as seconds from Jan 1 1970. This time.h mechanism fails around jan-feb, 2038.

>> and returns the address of variable rawtime which now holds the time?
Sorry, this is that pointer stuff you're trying to avoid. The &rawtime means that the address of rawtime is passed to time, and that time function can modify it. In C/C++, the arguments to a function are input only. By providing the input address, the function can modify the contents of the address to allow the variable argument to be modified.

Alternatively, you can write
    rawtime = time (NULL);
This approach looks easier. The example came from a link that I provided.

>> what does line 12 do?
12: localtime() takes in the rawtime, and creates a struct tm.
   I've added the stuct description in the code box - taken from the link:

Be very careful about the ranges and their interpretation when you walk through the debugger
  - they are not necessarily intuitive!
   tm_mday   day of the month        1-31
   tm_mon    months since January 0-11
   tm_year    years since                1900

>> what does line 14 do?
    strftime(str, sizeof(str) , "%d%b%Y", timeinfo);
  -- converts the struct tm object that you filled out in line 12 into a string according to the rules in the complex looking table in the strftime link I provided. strftime means string formatted time - converts one of the time representations into a string. This snippet is an example. We can work on getting the string into a form that is more suitable for your needs.

>> line 15 prints the character array str to the dos prompt so i can see it...
yes, just for debugging purposes.
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;  // you need this for the day of the month
int tm_mon;   // you need this for the month
int tm_year;  // you need this for the year
int tm_wday;
int tm_yday;
int tm_isdst;

Open in new window

>> create a filepath C:\2010\4\1\
As noted in a previous related question, you need
when opening up a file. BTW, opening a file uses a c-style string rather than a C++ string because the latter wasn't invented until sometime after the C++ file open mechanisms were established (at least that is what I have been taught).

Approach 1:
   Modify the code snippet from the localtime link slightly, adding in the drive letter and the hard-coded filename as shown in the Code box below. But, now you need to modify the buffer to remove a leading 0 in the month, if present. Do chapters 1-4 cover how to do this?

Approach 2:
You learned in a previous related question that you can use sprintf to format a c-style string. In that thread was an example of how to convert your three integers into a string:
      sprintf( buffer, "%d\\\\%d\\\\%d", year, month, day);
You could modify this to be:
      sprintf(str, "C:\\\\%d\\\\%d\\\\%d\\\\Example.txt", year, month, day);
if you wanted to. But then, for today's date. you still need to compute year, month, and day.

If you have:
    struct tm * timeinfo;
defined and filled in as above, then here is a pointer fact that you need to know:
   int year = timeinfo->tm_year;
puts the tm_year value into your year variable. Similar statements for your month and day. But, you will need to adjust the year and the month carefully into your normal ranges for year and month. Then the formatted c-style string will not have a leading 0 for the month.

Pick the approach which you feel most comfortable with.
strftime(str, sizeof(str), "C:\\\\%Y\\\\%m\\\\%d\\\\Example.txt", timeinfo);
// Output:
// C:\\2010\\04\\02\\Example.txt
// close, but you want C:\\2010\\4\\02\\Example.txt

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.