GIDForums  

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 02-Nov-2005, 21:51
penth penth is offline
New Member
 
Join Date: Nov 2005
Posts: 5
penth is on a distinguished road

ifstream and ofstream variable filenames


Hi,

I'm trying to write a program that takes a data file and formats it and then spits it out as a different file with proper formatting. I've got all of the major parts done. The only thing I'm having trouble with is that right now the input and output filenames are hard coded.

CPP / C++ / C Code:
  ifstream openFile ("BATCH002.DAT");
  if (openFile.is_open())
  {
	
    while (! openFile.eof() )
    {
	  
	  getline (openFile,line);

	  oneArray[q] = stripSpace(line);

	  q++;

    }

    openFile.close();

  }


and the output code

CPP / C++ / C Code:

	ofstream outputFile("OUTPUT.TXT");
	if (outputFile.is_open())
	{
		for (int k = 0; k < arrayHeight; k++)
			{
				if (oneArray[k] != "double" && oneArray[k] != "") outputFile << oneArray[k] << "\t\t\t\t" << twoInts[k] <<"\n";
			}
		
	outputFile.close;
	}
	else cout << "Error opening file.";



I would like to set .DAT files to open in this program by default so that when we double click on BATCH001.DAT or BATCH002.DAT the program will know that it needs to open that file in the stream.

Then I'd like to have the option to enter a filename for the output. I'd also like to add the date and .DAT to the end. So if I enter BigList the file will be called BigList 11-02-2005.DAT

I found some information on how to get the current date but had trouble getting it into a string. I think I found some info here that I will give a try, but I can't find anything about using variables as the filename.

Thanks for any help.
  #2  
Old 03-Nov-2005, 00:24
Paramesh's Avatar
Paramesh Paramesh is offline
Regular Member
 
Join Date: Sep 2005
Location: The Milky Way
Posts: 922
Paramesh is a jewel in the roughParamesh is a jewel in the roughParamesh is a jewel in the rough

Re: ifstream and ofstream variable filenames


Hi penth,

Welcome to the GID Forums.

Quote:
I would like to set .DAT files to open in this program by default so that when we double click on BATCH001.DAT or BATCH002.DAT the program will know that it needs to open that file in the stream.
For this you can use the command line arguments in the main function.
This is the syntax for the main function:
CPP / C++ / C Code:
 int main(int argc, char *argv[])

Where argc is the number of arguments,argv is a pointer to an array of character strings.
You can find more information about these in this link:
Command Line arguments

Quote:
Then I'd like to have the option to enter a filename for the output. I'd also like to add the date and .DAT to the end. So if I enter BigList the file will be called BigList 11-02-2005.DAT

We can use a command line argument to enter the file name.
For this, we are creating a string for storing the filename.
First, we add the commandline argument (like argv[1]) to the string stream.
Then we append the day, month and year.
at last we append the extension .dat

Then we store the contents in the string stream to std::string.
then we create output file with the name of the string.

Here is a complete sample program that demonstrated you how to do this:
CPP / C++ / C Code:

#include <ctime>                    //required to get the current date
#include <cstring>                  //required for string manipulation
#include <sstream>                  //required for converting int to string
#include <fstream>                  //required  for file i/o           

using namespace std;

int main (int argc, char* argv[])
{
  time_t timen;                      //time time_t
  struct tm * timet;                 //struct timet
  string ss;                         //string to hold the filename
  ostringstream oss;                 //used to convert int to string

  time ( &timen );                   //get the current time
  timet = localtime ( &timen );      //convert it into a structure timet

  oss << argv[1] << "-"              //add the command line argument
      << timet->tm_mday << "-"       //add the day, month and year
      << timet->tm_mon  + 1 << "-"
      << timet->tm_year + 1900
      <<".dat";                      //add .dat extension
      
     
  ss = oss.str();                    //ss now contains the filename
  cout << ss;                        //display ss to see the file name
  ofstream fout(ss.c_str());         //create the file     
  fout<<"Hello world";               //insert sample text
  
  return 0;
}


Suppose you give the command line as:
program.exe BigList

then the file will be created with the name:
BigList-3-11-2005.dat

I hope you know about time and string functions.
You can find more information by googling.

Best Regards,
Paramesh.
__________________

Don't walk in front of me, I may not follow.
Don't walk behind me, I may not lead.
Just walk beside me and be my friend.
  #3  
Old 03-Nov-2005, 09:42
penth penth is offline
New Member
 
Join Date: Nov 2005
Posts: 5
penth is on a distinguished road

Re: ifstream and ofstream variable filenames


It seems like I always forget a little bit of information. I've already used the argc and argv in the main() to get the command line arguments. The problem I have is it doesn't seem like the ofstream and ifstream will accept a variable name inside the () for an argument.

I've tried manually defining the string and declaring it as a const, but the program errors on compliing no matter value is inside the string.

c:\FileStream.cpp(17): warning C4267: '=' : conversion from 'size_t' to 'int', possible loss of data
c:\FileStream.cpp(36): error C2664: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstrea m(const char *,std::_Iosb<_Dummy>:penmode)' : cannot convert parameter 1 from 'const std::string' to 'const char *'
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Dummy=int
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
c:\FileStream.cpp(80): warning C4551: function call missing argument list
  #4  
Old 03-Nov-2005, 14:22
Paramesh's Avatar
Paramesh Paramesh is offline
Regular Member
 
Join Date: Sep 2005
Location: The Milky Way
Posts: 922
Paramesh is a jewel in the roughParamesh is a jewel in the roughParamesh is a jewel in the rough

Re: ifstream and ofstream variable filenames


Hi penth,

There is no way we could solve the problem unless you post the full code here.
Because c:\FileStream.cpp(17): implies that you have an error message in line 17.
But how do we know which line is line 17?

So Please post your full code here.

Regarding this:
Quote:
It seems like I always forget a little bit of information. I've already used the argc and argv in the main() to get the command line arguments. The problem I have is it doesn't seem like the ofstream and ifstream will accept a variable name inside the () for an argument.
It is already stated in the previous post.
We can use the ostringstream for that.
ostringstream class provides an interface to manipulate strings as if they were output streams.

So, in the previous example, if you give a command line argument such as Biglist, then a file name Biglist-dd/mm/yyyy.dat file will be created.
Note how the parameter is passed to the ofstream.

The char* is given to the string stream oss. Then it is converted to std::string.
The ofstream input is ss.c_str().

Regards,
Paramesh.
__________________

Don't walk in front of me, I may not follow.
Don't walk behind me, I may not lead.
Just walk beside me and be my friend.
  #5  
Old 03-Nov-2005, 14:24
penth penth is offline
New Member
 
Join Date: Nov 2005
Posts: 5
penth is on a distinguished road

Re: ifstream and ofstream variable filenames


Full Code

CPP / C++ / C Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstring>

using std::string;
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::setw;


string stripSpace(string s) {
  int br;
  while((br = s.find(" ")) != string::npos)
    s.erase(br, strlen(" "));
  return s;
}


int main()
{

    const int arrayWidth = 2;
	const int arrayHeight = 1000;
	string line;
	string oneArray[arrayHeight] = {"\0"};
	string inputfile = "BATCH002.DAT";
	int twoInts[arrayHeight] = {0};
	int twoArray[arrayHeight] = {0};

  int q = 0;

  ifstream openFile ("BATCH002.DAT");
  if (openFile.is_open())
  {
	
    while (! openFile.eof() )
    {
	  
	  getline (openFile,line);

	  oneArray[q] = stripSpace(line);

	  q++;

    }

    openFile.close();







for (int d = 0; d < arrayHeight; d++)
	{
	for(int e = 0; e < arrayHeight; e++)
	{
        if( oneArray[e] == oneArray[d])
		{
			++twoInts[d];
			if(e != d) oneArray[e] = "\0";

		}
	}
	}
	
	ofstream outputFile("OUTPUT2.TXT");
	if (outputFile.is_open())
	{
		for (int k = 0; k < arrayHeight; k++)
			{
				if (oneArray[k] != "") outputFile << oneArray[k] << "\t\t\t\t" << twoInts[k] <<"\n";
			}
		
	outputFile.close;
	}
	else cout << "Error opening file.";
  }

  else cout << "Unable to open file"; 

	return 0;
}
  #6  
Old 03-Nov-2005, 15:35
Paramesh's Avatar
Paramesh Paramesh is offline
Regular Member
 
Join Date: Sep 2005
Location: The Milky Way
Posts: 922
Paramesh is a jewel in the roughParamesh is a jewel in the roughParamesh is a jewel in the rough

Re: ifstream and ofstream variable filenames


Hi penth,

You said you used the command line arguments. But Where?
Ok. Lets discuss the program completely.

First, if you use using namespace std;, you can remove these:
CPP / C++ / C Code:
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::setw;

Then, you should define your main function as:
CPP / C++ / C Code:
int main (int argc, char* argv[])

Let us consider that you are giving an input like this:

program.exe BATCH002.DAT OUTPUT2.TXT

where the first file is the input file and the last one is the output file.
This means that
argv[1] is BATCH002.DAT
argv[2] is OUTPUT2.TXT

Now, to give the input filename to the ifstream, we can do like this:
CPP / C++ / C Code:
    const char* str = argv[1];
    ifstream openFile (str);

and for the output file, we can give like this:
CPP / C++ / C Code:
    const char* str2 = argv[2];
    ofstream outputFile (str2);

This is one way of giving the input.

The other way is the way is described earlier using the ostringstream, where you can also add date to the output file name.

Best Regards,
Paramesh.
__________________

Don't walk in front of me, I may not follow.
Don't walk behind me, I may not lead.
Just walk beside me and be my friend.
  #7  
Old 03-Nov-2005, 15:44
penth penth is offline
New Member
 
Join Date: Nov 2005
Posts: 5
penth is on a distinguished road

Re: ifstream and ofstream variable filenames


I took the argc and argv out because I was trying to simplify it by just using a string that I manually assigned.

To simplify the problem I basically want to replace this line:

CPP / C++ / C Code:
  ifstream openFile ("BATCH002.DAT");
with something like this

CPP / C++ / C Code:
string inputFileName = "\0";
cin >> inputFileName;

  ifstream openFile (inputFileName);

If I can get that working then I can take care of filling the actual inputFileName with whatever information I actually want inside the string.

My only problem is getting a string to work inside the constructor () instead of having to put "BATCH002.DAT"

Thanks for your help.
  #8  
Old 03-Nov-2005, 15:49
Paramesh's Avatar
Paramesh Paramesh is offline
Regular Member
 
Join Date: Sep 2005
Location: The Milky Way
Posts: 922
Paramesh is a jewel in the roughParamesh is a jewel in the roughParamesh is a jewel in the rough

Re: ifstream and ofstream variable filenames


Hi penth,

Quote:
If I can get that working then I can take care of filling the actual inputFileName with whatever information I actually want inside the string.

My only problem is getting a string to work inside the constructor () instead of having to put "BATCH002.DAT"
That is very simple.
here is how you do it:
CPP / C++ / C Code:
string inputFileName = "\0";
cin >> inputFileName;

  ifstream openFile (inputFileName.c_str());

where inputFileName.c_str() will return a const char*.

I hope i said this earlier itself.

Cheers,
Paramesh.
__________________

Don't walk in front of me, I may not follow.
Don't walk behind me, I may not lead.
Just walk beside me and be my friend.
  #9  
Old 03-Nov-2005, 15:51
penth penth is offline
New Member
 
Join Date: Nov 2005
Posts: 5
penth is on a distinguished road

Re: ifstream and ofstream variable filenames


THANK YOU! I knew it couldn't be as complicated as it was trying to be. I truly appreciate it.
 

Recent GIDBlogPrepping for deployment by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem with one variable bretter CPP / C++ Forum 1 16-May-2005 07:20

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 22:04.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.