Link to home
Start Free TrialLog in
Avatar of Irish97
Irish97

asked on

Reading a file

Experts,
       I need to read from a file fo this format..Please let me know how to do this..

a
Name1
Name2
Name3
//each segment seperated by a space
m
Date1
Date2
Date3

the and m signal the start of a command. I need to put all the elements associated with a particualr command in a vector for processing. There is no limit of how many of these segments are available, but there will be a bland line after the last command set to signal the end of the file.
Avatar of Irish97
Irish97

ASKER

I am sorry..I forgot to to confirm that each element has to be read as a string..ie..a, Name1, Name2, Name3 and Name4 need to be read into a vector and the same for the m command.
ASKER CERTIFIED SOLUTION
Avatar of sumant032199
sumant032199
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> you can use read function or fread function
>> and give the  sizeof(your_struct) as a parameter
>> in place of no of bytes to be read
It sounds like the date is stored in ASCII.  a binary read would not be a good idea.  You'll read the  newlines.  Besides its unlikey that each line is the same size.

>> fread() will be more useful if the file is ASCII (readable)
Why?  Both are used to ready data in binary form?
class CmdDat
{
private:
   char CmdLtr;  // Command letter
   vector<string> CmdPrm; // Command parameters.
public:
// some member accces functions, maybe a constructor or two.

   friend istream &operator >> (istream &In,CmdDat &Dat);
};

istream &operator >> (istream &In,CmdDat &Dat)
{
   string Lin;

   // Look for command letter.
   while (true)
   {
       getline(In,Lin);
       
       int Pos = Lin.find_first_not_of(' '); // Look for first non-space char.
       if (Pos != basic_string::npos) // If there is a non-space char.
      {
          Dat.CmdLtr = Lin[Pos]; // Set the command letter.
          break;
      }
   }

   // Get parameter lines until a blank line.
   while (true)  
   {
       getline(In,Lin); // Get the next line.

       if (Lin.length() == 0)  // If the line is empty.
          break; // Stop getting parameter lines.
       Dat.CmdPrm.push_back(Lin); // Add the command parameter to the list.
   }

   return In;
}
Instead of fread() I wanted to say
fscanf();