Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to read a file and parse it in C++?

Status
Not open for further replies.

Bella

Newbie level 6
Joined
Dec 22, 2003
Messages
11
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
90
how to parse *.list file in c++

start
name
units
2
begin
a: 12,0.7,12,12.5
b: bb, 23, 24, 10
c: cc, 23.5, 24.5, 12
d: dd, 22.5, 22.5, 13
e: 10,12,12
end
name1: abc,12, 12
name2: 12.5,12.5, 14
name3: 12.5,12.5,ab1,ab2,ab3
stop

The above is the text file sample.txt. I have to read the file and parse the above text file. How to parse each separately using C++?. Between begin and end, I have to parse each after ":" . Is there any simple logic to parse them?.
 

parse file to a particular position, c++

This is how you could do it:
But it's C for handling the file IO
Perhaps you can do it with filestreams too.

Code:
#include <stdio.h>

// global variable or membervariable of a class
containertypeYouWant container;

void parseFile(char * inifileName)
{
  char line[1024];  // Buffer for a line
  FILE * inifile;

  inifile = fopen(inifileName, "rt");

  while(fgets(line, sizeof(line) - 1 , inifile) != NULL)
    {
       // do we have to parse (are we seen begin and not seen end?)

       //search line for :
  
       //store stuff before : as identifiername in container
       
       //parse line after : to store values
    }

You'll have to work the lineparsing out yourself.
An easy way is converting the line to an std::string
Code:
std::string parseString = std::string(line);

Now you can use the search method of string
and store the information in the container

Code:
unsigned int position;
position = parseString.find(":");
if (position < parseString.size())
{
  // store method of container has 2 arguments
  // first is the identifier, second is the data
  // store method could parse the data when it has multiple values
   container.store(parseString.substr(0,position), 
                          parseString.substr(position+2));
  //                                                  ^
  //                                                  forget ':' and ' '
}

more information about std::string can be found here:
https://www.sgi.com/tech/stl/basic_string.html

btw, when you need to parse allot of files with a more extended syntax then Name = Value you could think of using Flex and Bison (updated Lex and YACC)
https://www.mactech.com/articles/mactech/Vol.16/16.07/UsingFlexandBison/


Antharax
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top