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.
Irish97Asked:
Who is Participating?
 
sumant032199Connect With a Mentor Commented:
You may need to construct a structure large enough to store 1 set of data in file. i.e. a,Name1,Name2,Name3
Then 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. This will directly put the data of that much bytes in the structure member's memory. You can use either address of(&) or a pointer to structure which must have sizeof(your_struct) bytes allocated.

fread() will be more useful if the file is ASCII (readable)
0
 
Irish97Author Commented:
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.
0
 
nietodCommented:
>> 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?
0
 
nietodCommented:
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;
}
0
 
sumant032199Commented:
Instead of fread() I wanted to say
fscanf();
0
All Courses

From novice to tech pro — start learning today.