[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

Why can't I open & read files with this code?

In Line 115 I have a vector of filepaths...but I get an error here when I compile...please tell me what I'm doing wrong..Thanks.


#include <time.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
//#include <afx.h>


using namespace std;


unsigned short GetTodaysDate(unsigned short &year, unsigned short &month, unsigned short &day)
{
	time_t rawtime;        //rawtime is variable of data type time_t, related to time.h
    struct tm * timeinfo; //timeinfo points to a struct of type tm, related to time.h
    char str[60];

    rawtime = time (NULL); //retrieves number of seconds from 1/1/70, in GMT, stores in address of rawtime
    timeinfo = localtime ( &rawtime ); //localtime takes rawtime, and creates a "tm" struct

   strftime(str, sizeof(str) , "%Y %m %d", timeinfo);  //formats the timeinfo struct into a string
//   printf(str);                                                       //outputs string to let me see if date is right
   
   year = atoi(&str[0]);   
   month = atoi(&str[5]);
   day = atoi(&str[8]);

   return (year, month, day);
}


string FindOneDayEarlier(unsigned short &year, unsigned short &month, unsigned short &day)
{
//months with 31 days: 1, 3, 5, 7, 8, 10, 12
//months with 30 days: 4, 6, 9, 11
//months with 28/29 days: 2

	day = day - 1; //decrement the day

    if (day == 0) //if day = 0, today must be 1st of the month
	{    
			if (month == 2 || month == 4 || month == 6 || month == 8 || month == 9 || month == 11 || month == 1)
			{
				day = 31;
			}

			if (month == 5 || month == 7 || month == 10 || month == 12)
			{
				day = 30;
			}
			if (month == 3)  //if not a leap year, who cares, just search, find nothing, skip, and decrement to 28
			{
				day = 29;
			}

			month = month - 1;
			if (month == 0)  //if this month is Jan, prior month will be Dec.
			{
				month = 12;  //if we are in Dec., we must be in prior year...so...
				year = year - 1; //we will never count back before year 2000, so it's always positive
			}
    }

   char buffer[40];
   sprintf( buffer, "C:\\\\%d\\\\%d\\\\%d\\\\ABC.txt", year, month, day);

   return string(buffer);
}


bool FileExist( string strFilepath )
{     
    // ifstream is used for reading files
	ifstream inf( strFilepath.c_str() );

    // If we couldn't open the output file stream for reading
    if (!inf)
    {
        return false;
    }
	else
		return true;	    
}

void GetValidFilepaths(unsigned short year, unsigned short month, unsigned short day, vector<string>& vFilePaths)
{

// Given today's date, get YESTERDAY's date in string form to be used in a file path
// then loop through past 9 days, and find out if filepath for each day is valid, or not
// if filepath is valid, save in a vector
	string strFilepath;
	int intNumDaystoLookBack = 9;
	int intCount = 0;  


	do
	{
		strFilepath = FindOneDayEarlier(year, month, day);//goes back in time, 1 day at a time

//  Given the FilePath for yesterday's date, find out if the Example.txt file exists
		if (FileExist(strFilepath))
		{
			intCount = intCount + 1;
            vFilePaths.push_back(strFilepath); // make note of the filepath and store it for future use
		}
	}while (intCount <= intNumDaystoLookBack);
}

string GetDataIntoString (vector<string> vFilePath)
{
	std::string strInput; //the String to read all data into

	int x = 0;
	for(x = 0; x <= 9; x++)
	{
		ifstream inf(vFilePath[x]); //ifstream is used for reading files
    
		// While there's stuff left to read
		while (inf)
		{
			inf >> strInput; // read stuff from the file into a string 
		}
	}

	return strInput;
}

int main()
{
// Get TODAY's date  
   unsigned short year = 0;
   unsigned short month = 0;
   unsigned short day = 0;

	GetTodaysDate (year, month, day);

	vector<string> vFilePaths;

//this goes back X number of days to retrieve file paths that are available and valid
    GetValidFilepaths (year, month, day, vFilePaths);

//this goes through the vector of valid file paths that lead to data, reads the file, puts the data into one, big string
	GetDataIntoString (vFilePaths);

    return 0;
}

Open in new window

0
shaolinfunk
Asked:
shaolinfunk
  • 12
  • 12
1 Solution
 
shaolinfunkAuthor Commented:
And here is my error log:
1>------ Rebuild All started: Project: junk, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'junk', configuration 'Debug|Win32'
1>Compiling...
1>Junk.cpp
1>c:\documents and settings\administrator\desktop\junk\junk\junk.cpp(116) : error C2664: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char *'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>Build log was saved at "file://c:\Documents and Settings\Administrator\Desktop\junk\junk\Debug\BuildLog.htm"
1>junk - 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Open in new window

0
 
phoffricCommented:
Remember?
ifstream inf(vFilePath[x].c_str());

Open in new window

0
 
phoffricCommented:
Not easy to remember all this stuff, especially when it appears inconsistent. Recall that the stream stuff came before the string stuff, so the streams still use the old c-style strings. and c_str() converts the string to c-style string.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
shaolinfunkAuthor Commented:
doh.  again.  the devil is in the details.
0
 
shaolinfunkAuthor Commented:
i accepted the wrong post.  it should've been the 7:22pm post and not the 7:24pm post.  does it matter?
0
 
phoffricCommented:
Given how few posts there are, I think anyone who searches will find the right answer :)
0
 
phoffricCommented:
Actually, the post accepted is just fine in that it explains things in more detail than the previous post.
0
 
shaolinfunkAuthor Commented:
Here I've hardcoded" x=0; x<=9;;x++"  in the for loop because i know the vector only runs from 0 to 9.

 But how do I not hardcode in the 9 and have the for loop run to whatever the upper bound of the vector is?
0
 
phoffricCommented:
Is this what you are looking for
        unsigned int x = 0;
        for(x = 0; x <= vFilePath.size(); x++)

Open in new window

0
 
shaolinfunkAuthor Commented:
Also, I am using a free stock market data file to test out the code.  Attached is the ABC.txt.  Why does ifstream only read the first unit of data, stop at the <space>, and not continue on to read the rest of the file?
ABC.txt
0
 
shaolinfunkAuthor Commented:
ah thx...i see how unsigned int is better than just int.
0
 
phoffricCommented:
I'll take a look. Suggestion, in future, do not close a question until you are reasonably sure all bases are covered. When you close a question, you may accept multiple posts even if there is only one contributor. This will then highlight all the useful posts that answer the question.
0
 
phoffricCommented:
I was getting up to speed with your latest code. What is this doing here?
Oh, I see - you changed the profile to use references. In that case, change the profile to return void since you are no longer returning anything via a return statement (nor are you assigning the return in the caller to anything).

That return compiles, but it does not return 3 things. Read all about it sometime - it's called the comma operator.
   return (year, month, day);

Open in new window

0
 
shaolinfunkAuthor Commented:
I misspeak...as I step through the code it DOES go through all of the ABC.txt's content.  but strInput is not accumulating ALL of the data...just the very, very last unit of information.  

When running to cursor to see the final strInput that is being returned the main function I expected to see ALL of the data you can see the ABC.txt....instead I just see the very last number...
0
 
shaolinfunkAuthor Commented:
for the 7:40pm comment, are you referring to the GetTodaysDate function?

so, should it be like this instead?

void GetTodaysDate(unsigned short &year, unsigned short &month, unsigned short &day)
{
   **return (year, month, day);**--->now deleted?
}
0
 
phoffricCommented:
void GetTodaysDate(unsigned short &year, unsigned short &month, unsigned short &day)
yes
return (year, month, day);**--->now deleted?
yes, or replace with return;
Usually when returning void, the return is left out, but no matter.
0
 
shaolinfunkAuthor Commented:
Would it help to zip up and upload the fake database I created to see if my code works?  
0
 
phoffricCommented:
OK
0
 
shaolinfunkAuthor Commented:
Here's my latest code + fake database to see if code works....
#include <time.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
//#include <afx.h>


using namespace std;


void GetTodaysDate(unsigned short &year, unsigned short &month, unsigned short &day)
{
	time_t rawtime;        //rawtime is variable of data type time_t, related to time.h
    struct tm * timeinfo; //timeinfo points to a struct of type tm, related to time.h
    char str[60];

    rawtime = time (NULL); //retrieves number of seconds from 1/1/70, in GMT, stores in address of rawtime
    timeinfo = localtime ( &rawtime ); //localtime takes rawtime, and creates a "tm" struct

   strftime(str, sizeof(str) , "%Y %m %d", timeinfo);  //formats the timeinfo struct into a string
//   printf(str);                                                       //outputs string to let me see if date is right
   
   year = atoi(&str[0]);   
   month = atoi(&str[5]);
   day = atoi(&str[8]);
}


string FindOneDayEarlier(unsigned short &year, unsigned short &month, unsigned short &day)
{
//months with 31 days: 1, 3, 5, 7, 8, 10, 12
//months with 30 days: 4, 6, 9, 11
//months with 28/29 days: 2

	day = day - 1; //decrement the day

    if (day == 0) //if day = 0, today must be 1st of the month
	{    
			if (month == 2 || month == 4 || month == 6 || month == 8 || month == 9 || month == 11 || month == 1)
			{
				day = 31;
			}

			if (month == 5 || month == 7 || month == 10 || month == 12)
			{
				day = 30;
			}
			if (month == 3)  //if not a leap year, who cares, just search, find nothing, skip, and decrement to 28
			{
				day = 29;
			}

			month = month - 1;
			if (month == 0)  //if this month is Jan, prior month will be Dec.
			{
				month = 12;  //if we are in Dec., we must be in prior year...so...
				year = year - 1; //we will never count back before year 2000, so it's always positive
			}
    }

   char buffer[40];
   sprintf( buffer, "C:\\\\%d\\\\%d\\\\%d\\\\ABC.txt", year, month, day);

   return string(buffer);
}


bool FileExist( string strFilepath )
{     
    // ifstream is used for reading files
	ifstream inf( strFilepath.c_str() );

    // If we couldn't open the output file stream for reading
    if (!inf)
    {
        return false;
    }
	else
		return true;	    
}

void GetValidFilepaths(unsigned short year, unsigned short month, unsigned short day, vector<string>& vFilePaths)
{

// Given today's date, get YESTERDAY's date in string form to be used in a file path
// then loop through past 9 days, and find out if filepath for each day is valid, or not
// if filepath is valid, save in a vector
	string strFilepath;
	int intNumDaystoLookBack = 9;
	int intCount = 0;  

	do
	{
		strFilepath = FindOneDayEarlier(year, month, day);//goes back in time, 1 day at a time

//  Given the FilePath for yesterday's date, find out if the Example.txt file exists
		if (FileExist(strFilepath))
		{
			intCount = intCount + 1;
            vFilePaths.push_back(strFilepath); // make note of the filepath and store it for future use
		}
	}while (intCount <= intNumDaystoLookBack);
}

string GetDataIntoString (vector<string> vFilePath)
{
	std::string strInput; //the String to read all data into

	unsigned int x = 0;
	for(x = 0; x <= 9; x++)  //vFilePath.size()
	{
		ifstream inf(vFilePath[x].c_str()); //ifstream is used for reading files
    
		// While there's stuff left to read
		while (inf)
		{
			inf >> strInput; // read stuff from the file into a string 
		}
	}

	return strInput;
}

int main()
{
// Get TODAY's date  
   unsigned short year = 0;
   unsigned short month = 0;
   unsigned short day = 0;

	GetTodaysDate (year, month, day);

	vector<string> vFilePaths;

//this goes back X number of days to retrieve file paths that are available and valid
    GetValidFilepaths (year, month, day, vFilePaths);

//this goes through the vector of valid file paths that lead to data, reads the file, puts the data into one, big string
	string strInput;
	strInput = GetDataIntoString (vFilePaths);

    return 0;
}

Open in new window

2010.zip
0
 
phoffricCommented:
>>  but strInput is not accumulating ALL of the data...just the very, very last unit of information.
Yes, you are successfully reading the files and storing each token (a set of chars using a white-space delimiter) into a string variable. But you are not accumulating them.

I think this is new topic - your program is reading the files just fine. You just need better processing once you have the data. But here are some questions.

1. You use the number 9, yet you read in have 10 files. Why not have the desired number of files and this number match? Also, for a particular run, how do you determine how many files you want to read in?

2. Don't you want to separate one line from another in your string; and if not, then what kind of delimiters do you need between tokens in a line; and do you need a different token for EOL?
0
 
shaolinfunkAuthor Commented:
Ok, will post new question...and they are EXACTLY the questions you pose.
0
 
phoffricCommented:
You have to tell us how to determine the number of files you want to read.
0
 
shaolinfunkAuthor Commented:
The number of files to accumulate is set by user to some number.  For this example let's just settle on 9, meaning I want to accumulate at least 9 days worth of ABC.txt file data.

I just created the new question here:
http://www.experts-exchange.com/Programming/Languages/CPP/Q_25669250.html
0
 
phoffricCommented:
OK, but how do you want the user to be able to enter this number: via command line, via console prompt, via data in a file, or what?
0

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

  • 12
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now