Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

date function

Status
Not open for further replies.

rtnMichael

Programmer
Aug 5, 2002
152
US
Hi,
I want to create a file with just the date in it. I know I can call date(), but how do I do it to print to a file?

Thanks :)
M
 
use snprintf,copy your data into a buffer,and write it into a file,it is so easy like:

snprintf(buf, 32, "%d\n", (int) getpid());
write(fd, buf, strlen(buf));
 
#include <stdio.h>
#include <sys/types.h>
#include <time.h.

main(int argc, char **argv)
{
FILE *fp;
time_t the_time;
struct tm *loc_time;

the_time = time(0L);
lc_time = gmtime(&the_time);

fp = fopen(&quot;test.txt&quot;, &quot;w&quot;);
fprintf(fp, &quot;%02d-%02d-%02d&quot;, lc_time->tm_mday, lc_time->tm_mon+1, lc_time->tm_year % 100);
fclose(fp);
}
 
ok, now I have a new one for you....what if I wanted to get the date and name the file with the real time current date?
 
...
char fileName[15];
sprintf(fileName,&quot;%04d%02d%02d&quot;, loc_time.tm_year, loc_time.tm_mon, loc_time.tm_mday);
fp = fopen(fileName, &quot;w&quot;);
...

Ex. the file will be named &quot;20020807&quot;.
 
Use ctime() to get the current date if your application runs on Linux or Unix.See the reference.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top