×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Reading from and Writing To a File

Reading from and Writing To a File

Reading from and Writing To a File

(OP)
I need to log to a file say a.txt the following values:
current date,current time,string,string

For the path of a.txt, i need to read from a file called info.properties which has a lot of parameters and their values in the following format:
Status = on
Path = here is the path of the a.txt

Now i need to read from the above properties file in the following manner:

String s = valueOf("Path");

And then I log the info into the file specified by this path. Some sample code would be really helpful as I am novice to C++. Code to retrive the date and time is also needed.

Thanx in Advance

RE: Reading from and Writing To a File

benaam,

    When I first stared this, I didn't realize just how involved the answer would be. I do something similar in BCB but I use VCL which makes things much easier. Since you don say which compiler you are using, I will try to use the STL. My time is very limited so I won't be able to give you a complete answer but I will try to give you some hints to finish up on you own. I also don't have time to compile and test my code so expect many errors.


    First, You are asking three things. Each could be a seperate thread. You are asking how to do file input and output. You are asking how to use the data from a file you read. You are asking how to get the date and time.

    Lets start with the date and time first. The header file time.h includes numerous time and date fuctions. To get day and time, you might do something like:

#include <iostream>
#include <time>

int main()
{
    // Set up the structure.
    time_t tval;
    struct tm *now;

    // Get the current date and time
    tval = time&#91;NULL];
    now = localtime(&tval);

    // Time
    int Second = now->tm_sec;
    int Minute = now->tm_min;
    int Hour = now->tm_hour;

    // Date
    int Day = now->tm_mday;
    int Month = now->tm_mon+1; // Month is offset by one
    int Year = now->tm_year;

    cout << "The date is" << Month << "-" << Day << "-" << Year << endl;
    cout << "The time is << Hour << ":" << Minute << ":" << Second << endl;

    return 0;
}


    For opening and closing files, I prefer streams. The header for file stream (input and output) is fstream.h.

#include <iostream>
#include <fstream>
#inclide <string>

int main()
{
    // Pick up ini file
    ifstream IniFile; // stream set up
    IniFile.open("Info.ini"); // I changed the name of the file to Info.ini from Info.properties

    // If the file exists and opens without errors
     if (IniFile)
     {
            // Everything OK, get data
            IniFile.unsetf(ios::skipws);// don't skip white space

            string ImpLine;             // import line
        // NOTE: If using BCB 5 or C++ 5.5, getline has a bug. See Borland Article ID #21145
        // This was fixed in a recent patch
            while (getline(IniFile, ImpLine, '\n'))
            {
                // While there is data to get then do something
            if (!ImpLine.empty())
                {
                // something
                // something
                // Set up LogPath somewhere here but don't forget about variable's scope
             }
         }
     }

     // You could put some error test in here, too, but I didn't

     ofstream LogFile; // stream set up
     LogFile.open(LogPath.c_str(), ios::app); // Open for append, not overwrite

     if (!LogFile)
     {
       // Opps! No file or error
        return 1;
     }
     else
     {
        LogFile << "We can put in date and time and anything else here, too." << endl;
        LogFile << "The date is" << Month << "-" << Day << "-" << Year << "," << flush; // keep on same line in file
        LogFile << "The time is" << Hour << ":" << Minute << ":" << Second << "," << flush; // keep in same line in file
        LogFile << LogPath << "," << StatusVariable << endl;
     }

    // Close files
    LogFile.close();
    IniFile.close();

    return 0;
}


    Finally, you want to parse the input lines from your input line. I'm not certain what you mean by "String s = valueOf("Path")." Is "valueOf" a function or what? You may need to clarify this if my next hints don't help. Since I'm not clear about what you mean, I'm just going to suggest you look at your string functions. A couple that I recommend are find and length. For example:

string WorkString = ImpLine; // So ImpLine doesn't get trashed

int StrLen = WorkString.length(); // length of string
int EqualPlace = WorkString.find("=", 0); where the = sign is in the string.

// Now you know where the equal sing is and the length of the string,
// You can get what is on the right hand side and the left hand side of the equal sign.


    One other suggestion is to use a trim function to remove any spaces from each side of your new strings to make it easier to find your path and status.


James P. Cottingham
www.ivcusa.com

RE: Reading from and Writing To a File

First of all Thanx for the code. I would see whether that is helpful to me.

Let me make things more clear.
I have a properties file. That file goes this way:
Path = "c:/somedir/somefile


Now, I need to the valus of the path from this file and write to the file specified in the Path variable.
valusOf is not a function. It was just pseudoCode.I wanted to say that i need to read the value of Path variable from the file.

RE: Reading from and Writing To a File

(OP)
First of all Thanx for the code. I would see whether that is helpful to me.

Let me make things more clear.
I have a properties file. That file goes this way:
Path = "c:/somedir/somefile


Now, I need to the valus of the path from this file and write to the file specified in the Path variable.
valusOf is not a function. It was just pseudoCode.I wanted to say that i need to read the value of Path variable from the file.

RE: Reading from and Writing To a File

benaam,


// We'll start by making a temp copy
string WorkString = ImpLine;

// We'll need the string length
int StrLen = WorkString.Length();

// Next, let's find the = position
int EqlSignPos = WorkString.pos('=');

// If the line has an equal sign, we'll process it
if (EqlSignPos > 0)
{
    // Found equal sign;
    // Get the first part of the string, skipping the = signs
    string FirstPart = WorkString.substring(0,EqlSignPos-2);

    // Now lets break about the string again
    AnsiString SecondPart = WorkString.substring(EqlSignPos+1, StrLen);

    // Set up variables
    if (FirstPart == "Status ")
    {
        IniStat = SecondPart;  // IniStat must have been previously initalized
    }

    if (FirstPart == "Path ")
    {
        IniPath = SecondPart;  // IniPath must have been previously initalized
    }

}


    Again, I haven't had time to test this. Another thing you can do is trim off excess spaces from the strings.

James P. Cottingham
www.ivcusa.com

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close