#include <stdio.h>
#include <time.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main ()
{
  ofstream file;
  stringstream ss;
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  char g[30];
  char buffer[10];
  itoa(timeinfo->tm_mday,buffer,10);
  strcat(g,buffer);  
  strcat(g,"-");
  itoa(timeinfo->tm_mon+1,buffer,10);
  strcat(g,buffer);
  strcat(g,"-");
  itoa(timeinfo->tm_year+1900,buffer,10);
  strcat(g,buffer);
  
  file.open((const char*)g, ios_base::app);
  if (!file) cout<<"error"<<endl;
  file<<"success!"<<endl;
  file.close();
  system("PAUSE");
  return EXIT_SUCCESS;
}

The file does not want to be opened - Can anyone help me?

Edited 6 Years Ago by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

why don't you just use sprintf()? With sprintf() you can do all that in one line of code. Do not put spaces in the date string because many programs have problems with the spaces, and arrange the string so that the file names can be easily sorted using Windows Explorer or some other program.

char filename[40];
sprintf(filename,"%04d%02d%02d", timeinfo->tm_year+190, 
    timeinfo->tm_mon,timeinfo->tm_mday);

>>file.open((const char*)g, ios_base::app);
The typecase is unnecessary.

>>if (!file) cout<<"error"<<endl;
It's good that you make that check, but if open fails then don't execute the lines that follow. So you should code this:

if( !file.is_open() )
{
    cout << "error\n"; // endl is unnecessary
}
else
{
   // do something
}

Edited 6 Years Ago by Ancient Dragon: n/a

This question has already been answered. Start a new discussion instead.