Thread: Automatically dating an output file created by ofstream

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    6

    Automatically dating an output file created by ofstream

    I am trying to create a program that stores some data in a file then closes it. I need the file to be named with the date and time of when it was closed by the program. I am using ofstream to write the file out and I am using a string variable that has the date in it.

    This calls my function that gets the time and date from the computer and stores it in a variable :

    Code:
    dateTimeName = fileTime();
    This is the fileTime() function :

    Code:
    string fileTime() 
    {
         time_t rawtime;
         struct tm * timeinfo;
    
         time ( &rawtime );
         timeinfo = localtime ( &rawtime ); 
         
         return (asctime (timeinfo));
      
    }
    This trys to name the output file with the date and time.

    Code:
    outf = dateTimeName; 
    ofstream outFile(outf.c_str());
    The trouble is it just refuses to work, if I give it an actual static string such as "test.txt" it will work fine but if I give it a variable which is a string it wont create the file.

    What do i need to do to get it to work ?

  2. #2
    Banned
    Join Date
    Jun 2005
    Posts
    594
    Here this is a program i wrote where i put part of the date in
    the file name, this code also show you how you can change the
    date.

    Code:
    #include <iostream>
    #include <fstream>
    #include <time.h>
    #include <string>
    #include <vector>
    #include <process.h>
    
    using namespace std;
    
    int main()
    {
    	struct tm when;
    	__time64_t now;
    	_time64( &now );
    	when = *_localtime64( &now );
    	vector<string> vDate;
    	char * date;
    	date = asctime( &when );
    	string sDate;
    	string sDate3;
    	sDate = date;
    	sDate3.insert(0, sDate, 0, 10);
    	sDate3 += ".txt";
    	fstream file;
    	file.open(sDate3.c_str(), ios::in);
    	if(!file.fail())
    	{
    		sDate3.insert(0, "type \"");
    		sDate3.insert(20, "\"");
    		system(sDate3.c_str());
    		cout << endl << endl;
    		cout << "Press any key to Continue!" << endl;
    		cin.get();
    	}
    
    	char * date2;
    	string sDate2;
    	string sDate4;
    	string sInfo;
    	int quanity;
    	bool EXIT = false;
    	while(EXIT == false)
    	{
    		cout << "Enter Customer Info : " << endl;
    		getline(cin, sInfo, '\n');
    		cout << "Enter Quanity : ";
    		cin >> quanity;
    		quanity -= 20;
    		if(sInfo[0] == '\0')
    		{
    			EXIT = true;
    		}
    		else
    		{
    		cin.ignore();
    		if(quanity < 0)
    		{
    			cout << "Quanity Must be more then 20" << endl;
    			cout << "Re enter the amount : ";
    			cin >> quanity;
    			cin.ignore();
    		}
    			for(int i = 0; i != 3; i++)
    			{
    				when.tm_mday = when.tm_mday + quanity;
    				_mktime64( &when );
    				date2 = asctime( &when );
    				sDate2 = date2;
    				sDate4.insert(0, sDate2, 0, 10);
    				vDate.push_back(sDate4);
    				sDate4 += ".txt";
    				fstream file1;
    				file1.open(sDate4.c_str(), ios::app | ios::out);
    				if(i == 0)
    				{
    					file1 << sInfo << endl;
    				}
    				else
    				{
    					file1 << endl << "*** ORIGINAL REMIND DATE " << vDate[0] << " ***" << endl;
    					file1 << sInfo << endl << endl;
    				}
    				file1.close();
    				sDate2.clear();
    				sDate4.clear();
    			}
    		}
    	}
    	return 0;
    }

  3. #3
    Registered User
    Join Date
    Jul 2005
    Posts
    6
    Thanks ill have a look through it.

  4. #4
    Registered User
    Join Date
    Jul 2005
    Posts
    6
    I am sorry but I am finding your example rather complex to understand ( I am not a good programmer ). I had another look around and have been trying to use this example :



    Code:
      time_t rawtime;
      struct tm * timeinfo;
    
      time ( &rawtime );
    
      timeinfo = localtime ( &rawtime );
    
    
     cout << asctime (timeinfo);
    This works perfectly but I just want to get it into the filename. I can
    now name the file using a variable thats a character array but I am now stuck on getting the string that the code fragment above produces into the char array in the fragment below. Surely it must be simple as a string is just a character array ?

    Code:
    char testing[] = "testing.txt" ;
    ofstream dataStream(testing);
    If I set the array to the length of the string , for example :

    Code:
    char testing[26] ;
    then try and fill it with the time

    Code:
     testing[26] = asctime (timeinfo);
    I get this compile error :

    invalid conversion from `char*' to `char'

    Any help much apreciated

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by Jeff21
    If I set the array to the length of the string , for example :


    Code:
    char testing[26];

    then try and fill it with the time


    Code:
    testing[26] = asctime (timeinfo);

    I get this compile error :

    invalid conversion from `char*' to `char'
    First off, the valid indicies for that array are from 0 through 25. You then attempt to assign a whole character string (consisting of many characters) into a single character (this is where you get the "invalid conversion" error) at an index that is invalid (index 26 is outside the valid range of indicies). You need to use strcpy to copy the time string into the array.

    Now, on to your other problem. The asctime function returns a string in the general form of (for example): "Mon Aug 01 08:06:26 2005". On my system (Win XP), if I go to explore my computer and create a new file in some directory and try and type in a filename similar to that string, the system won't let me get past the first ":". In fact it beeps and puts up a little tooltip window that says (and I quote): "A filename cannot contain any of the following characters: \/:*?"<>|" Therefore, I suspect that the reason you can't do what you are trying to do is that the time string you are using to name your file is invalid.

    The solution to that would seem to be try using a different format of time, perhaps "Mon Aug 01 08-06-26 2005" for example.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Jul 2005
    Posts
    6
    Thanks for the post, I never thought of the problem with the date format using colons. Although I had yet to get to a point where that was going to be my problem.

    I have a question regarding strcpy, in the examples I have been looking at on cpluplus.com's reference page it copys a string character array to a character array :

    Code:
    /* strcpy example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str1[]="Sample string";
      char str2[40];
      char str3[40];
      strcpy (str2,str1);
      strcpy (str3,"copy successful");
      printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
      return 0;
    }

    The trouble is I think the value returned from asctime is a std::string rather than a character array string so I get a compile error when I try and use strcpy to copy the returned date/time into the testing array.


    Am I correct or truly lost ?

  7. #7
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    If it was a std::string, that is correct, you would have a problem. However, the function does retrun a char* ( http://cppreference.com/stddate/asctime.html ).

    Note that the .c_str() member function of std::string returns a character array form of the string (however, if you need to copy this value, do use strcpy as you normally would).

    What code exactly is giving you trouble?
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  8. #8
    Registered User
    Join Date
    Jul 2005
    Posts
    6
    Thanks alot for your post, it fixed the problem. I was preety sure my asctime was giving me a std::string due to my compile errors so I used .c_str() and it fixed it. It now gets the date and time, converts it to a character array and then copies that array to the character array that names the file.

    Code:
    char testing[26];
    ofstream dataStream(testing);
    string         temporyDate;
    
    ----- More code goes Here -----
    
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
      
    temporyDate = asctime (timeinfo);
      
      
     
    strcpy (testing, temporyDate.c_str());

    The program is still not creating the file although it compiles with no errors. I am preety sure this is exactly what hk_mp5kpdw was talking about with the illegal characters such as ':'.


    Looking at cppreference.com strftime looks like what I should be using although I need to play around to find the correct syntax to give me the date structure I want.

  9. #9
    Registered User
    Join Date
    Jul 2005
    Posts
    6
    Well I have managed to get strftime working and it names the file perfectly. Thanks for eveyones help and here is the code that got it working :


    Code:
    char fileName[20];
    
    struct tm *ptr;
    time_t tm;
    
      
    tm = time(NULL);
    ptr = localtime(&tm);
    strftime(fileName ,20 , "%d-%m-%Y@%H%M.txt",ptr);
    
    
    ofstream dataStream(fileName);
    Hope this can help some one else.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  4. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM
  5. Simple File Creation Algorithm
    By muffin in forum C Programming
    Replies: 13
    Last Post: 08-24-2001, 03:28 PM