Hi I want to increment file number with date e.g 19-FEB-09-1.dat, 19-FEB-09-2.dat .... So in the write function after it runs for certain number of times say 12 the file number then increments to next one. However, if the file number already exists it then move to next number to write to file. Ignore the file read command in my code.

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <time.h>
#include <conio.h>

using namespace std;

void WriteToFile(const char *filename, int ArraySize);
int _tmain(int argc, _TCHAR* argv[])
{
	static const char filename[] = "data.dat";
	int ArraySize=10;
	WriteToFile(filename, ArraySize);
	return 0;
}


void WriteToFile(const char *filename, int ArraySize)
{

	double *read_dist=new double[ArraySize];
	double *read_ampl=new double[ArraySize];
	int i;
	double c[10]={1.23578,2,3,4,5,6,7,8,9,10};
	double d[10]={5,6,7,8,9,4,3,2,3,4};
	double *dist=c;
	double *ampl=d;

	 //while( !_kbhit() )

	//{      
	 //FILE NUMBER INCREMENT

		std::ofstream fileout(filename,ios::out | ios::binary );
		if(!fileout)
		 { 
		 std::cout << "Cannot open file to write.\n"; 
		 } 
			for(int n=0;n<12;n++)
			{
			fileout.write((char *) dist, sizeof(double)*ArraySize);  
		    fileout.write((char *) ampl, sizeof(double)*ArraySize);
			}
 		   fileout.close();
	//}
 
    }

line 46 writes the same array to the same file 12 times. And the use of the asterisk on that line for *ArraySize is also illegal because ArraySize is not a pointer. Even removing the asterisk its still wrong because you don't want sizeof(ArraySize) because you already know the array size. What you want is ArraySize * sizeof(double) . BTY you did it correctly on the very next line.

The filename is incorrect because it doesn't do anything with the date or increment the number. You have to format the file name to accomplish that.

After getting the number you want to use in the filename you have to find out if a file already exists with that name. The easiest way to do that is to try to open the file for reading. If it does not exist then the open file fail and when that happens increment the number, reformat the filename, and do try it again.

Here's a simple way to format the file name

#include <string>
#include <sstream>
<other includes here>

...
string filename;
int fileno = 1;
string date = "19-FEB-09";
do {
    stringstream str;
    // format the filename here
    str << date << "-" << fileno << ".dat";
    filename = str.str();
    ++fileno; // increment for next loop iteration
    // attempt to open for read
    ifstream in( filename.c_str() );
} while( !in.is_open() );

First of all its not a home work, I have provided a dummy data style as I am working in MATLAB and I need to write the data from a sensor to a file that can only be done due to C++ interface requirement. Since I have little experience so I cannot make it work. I hope some one helps me
I do not know, how to do the following, otherwise I know the flow how to do,

After getting the number you want to use in the filename you have to find out if a file already exists with that name. The easiest way to do that is to try to open the file for reading. If it does not exist then the open file fail and when that happens increment the number, reformat the filename, and do try it again.
???

I already posted the code that checks the filename to see if it exists or not. If the filename does not exist then that loop will exit and the filename is ready to use in the output file. I see that I forgot to increment the counter, so I just now added that to my post above.

How are you formatting the date part of the filename ? Do you already know how to do that ?

My comment has nothing to do with your code, but I am curious about this:

Hi I want to increment file number with date e.g 19-FEB-09-1.dat, 19-FEB-09-2.dat

Have you ever considered "big endian" date format? that is to say a filename format based on the date such as the following?

  • 2009-02-19~001.dat
  • 2009-02-19~002.dat
  • etc.

I mention this because if you've got directories full of data files, it makes life a lot easier if they automatically sort themselves in a more coherent manner.

You are right Dave -- I wrote a program at work once that used filenames with dates in MMDDYYYY format and lived to regret it because the program generated a new file every day. The next time I revised that program that was the first thing I changed.

I tried but it concatenates the file names e.g 20-FEB-08_120-FEB-08-2

std::string  filename;
	int fileno = 1;
	struct tm * timeinfo;
	char buffer [80];
	time_t rawtime; 
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	strftime (  buffer, 80,"%d-%b-%y", timeinfo );
	 
	result += buffer;
	  
	//cout<<result.c_str()<<endl; //without append
	std::ostringstream oss;
	oss << result << '_' << fileno;
	filename = oss.str();
	 if(0 == access(filename.c_str(), 0))
        {
                std::cout << "File exists" << std::endl;
				fileno+=1;
				oss << result << '_' << fileno;
				filename = oss.str();
        }
 
	cout<<filename.c_str()<<endl;

Would this concatenation result += buffer; have anything to do with it?

[edit]Sorry, I was only skimming your code. In my head, I kinda see something like this.

#include <iostream>
#include <string>
#include <ctime>

bool make_filename(std::string &filename, int i)
{
   time_t now; 
   if ( std::time ( &now ) != (time_t)-1 )
   {
      struct tm *local = std::localtime(&now);
      if ( local )
      {
         char timestamp[11], name[19];
         if ( std::strftime(timestamp, sizeof timestamp, 
                            "%Y-%m-%d", local) )
         {
            if ( std::snprintf(name, sizeof name, 
                               "%s~%03d.dat", timestamp, i) > 0 )
               filename = name;
               return true;
            }
         }
      }
   }
   return false;
}

int main()
{
   std::string filename("");
   for ( int i = 1; i < 15; ++i )
   {
      if ( make_filename(filename, i) )
      {
         std::cout << filename << '\n';
      }
   }
   return 0;
}             

/* my output
2008-02-20~001.dat
2008-02-20~002.dat
2008-02-20~003.dat
2008-02-20~004.dat
2008-02-20~005.dat
2008-02-20~006.dat
2008-02-20~007.dat
2008-02-20~008.dat
2008-02-20~009.dat
2008-02-20~010.dat
2008-02-20~011.dat
2008-02-20~012.dat
2008-02-20~013.dat
2008-02-20~014.dat
*/
This article has been dead for over six months. Start a new discussion instead.