Solved

Structures and Reading in a file

Posted on 2004-10-05
12
371 Views
Last Modified: 2010-04-15
Hello All,  

I am stuck and have been stuck for a while with this problem

I have defined structs within my program and need to read in the contents of a file and store it into the struct variables

eg file input format

1:Item1:Description:Price:Quantity

and the struct called itemStruct has the variables defined

ID, ItemName, Description, Price, Quantity

how would i read the contents of the file and store it into the struct variables?  I know that i need to tokenize the contents of the file based on the token : but am really lost with the process to do this

i also think that a linked list needs to be created and used to link each record within the file

Any help would be greatly appreciated

Thank you
0
Comment
Question by:jakekula
12 Comments
 
LVL 5

Expert Comment

by:lwinkenb
ID: 12235045
To read in from the file, use the functions:
fopen()
fread() or fgets() or fscanf()
fclose()

If you used fscanf() to read in from the file, then you can assign your variables directly.  Otherwise, you will need to parse the line you read in from the file to extract the variable values.  A good function to use for that would be strtok().  There is an example on how to use the strtok() function at http://www.cplusplus.com/ref/cstring/strtok.html
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12235326
The struct should look like that:

struct Article
{
     int      id;
     string  item;
     string  description;
     double price;
     int       quantity;
};

You'll need

#include <string>
using namespace std;

above.

To read from file i would use ifstream class:

#include <iostream>
#include <fstream>
using namespace std;


To open the file use:

         ifstream ifs("input.dat");    // input.dat from current directory

You could check the stream by

        if (ifs.fail())
        {
            cout << " error " << endl;
        }

To read the file use

        string line;
        while (getline(ifs, line))
        {
              ....
        }

That reads any line from input file. Finally close the stream:

       ifs.close();

To get the tokens from line you could use istringstream class.

Add #include <sstream> to the include statements. Then you could parse the string like that:


      Article* lineToArticle(const string& line)
      {
            Article* pArt = new Article;
            size_t pos = line.find(':');
            size_t lpos = pos;
            if (pos == string::npos)
                 return NULL; // error
            istringstream iss1 (line.substr(0, pos)); // feed stringstream by input line
            iss1 >> pArt->id;
            // pArt->item
            lpos = pos+1;
            pos = line.find(':', lpos);        
            if (pos == string::npos)
                 return NULL; // error
            pArt->item = line.substr(lpos, pos-lpos);

            // do the same with pArt->description
            ....
            // pArt->price        
            lpos = pos+1;
            pos = line.find(':', lpos);        
            if (pos == string::npos)
                 return NULL; // error
            istringstream iss2 (line.substr(lpos, pos-lpos)); // feed stringstream by input value
            iss2 >> pArt->price;

            // pArt->quantity
           
            istringstream iss3 (line.substr(lpos));
            iss3 >>pArt->quantity;
      }
      return pArt;
}

Regards, Alex

0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 12235367
This is the C forum Alex, not C++.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12236208
@lwinkenb: Thanks. My fault. I opened the wrong directory.

@jakekula: I'll convert it to C

Regards, Alex



0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 168 total points
ID: 12237339
// compiles as article.c

#include <iostream.h>
#include <fstream.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

typedef struct Article
{
    int     id;
    char    item[25];
    char    description[33];
    double  price;
    int     quantity;
};


int readInputFile(const char* pszFile)
{
    FILE*  pFile = NULL;
    char   line[256] = { '\0' };
    struct Article* pArt = NULL;
    int    len = 0;
   
// To open the file use:
    pFile = fopen("input.dat", "r");    // input.dat from current directory

// You could check the stream by

    if (pFile == NULL)
    {
        printf("error=%d\n", errno);
        return (int)errno;
    }

// To read the file use

    while (fgets(line, 256, pFile))
    {
       // eliminate newline char
       len = strlen(line);
       if (line[len-1] == '\n')
           line[--len] = '\0';
      // ....
    }

// That reads any line from input file. Finally close the stream:

   fclose(pFile);

   return 0;
}
// To get the tokens from line you could use istringstream class.

// Add #include <sstream> to the include statements. Then you could parse the string like that:


struct Article* lineToArticle(const char* pszLine)
{
    struct Article* pArt;
    char*           line = NULL;
    char*           psz  = NULL;

    pArt = (struct Article*)malloc(sizeof(struct Article));
    line = strdup(pszLine);
    psz  = strchr(line, ':');
    if (psz == NULL)
         return NULL; // error
    *psz = '\0';
    pArt->id = atoi(line);

    line = ++psz;
    psz  = strchr(line, ':');
    if (psz == NULL)
         return NULL; // error
    *psz = '\0';
    strcpy(pArt->item, line);

    // do the same with pArt->description
    // ....


    // pArt->price        
    line = ++psz;
    psz  = strchr(line, ':');
    if (psz == NULL)
         return NULL; // error
    *psz = '\0';
    pArt->price = atof(line);

    // pArt->quantity
    line = ++psz;
    psz  = strchr(line, '\n');
   
    return pArt;
}

Regards, Alex


0
 
LVL 9

Assisted Solution

by:ankuratvb
ankuratvb earned 166 total points
ID: 12238198
Hi,

If your program is the one that will be doing the storing as well,you can use fwrite() to write the entire structure to file in one go,and read it back using fread().You can read into a struct variable,so it'll read the values into the respective variables and you dont have to do it manually.

0
 
LVL 3

Expert Comment

by:aravindtj
ID: 12250561
Hi all,
 Beware of using structures. It may not be allocated the exact storage space as you expected. The compiler may optimize the storage allocation for that. So, take care when manipulating structures.

:)
0
 
LVL 1

Assisted Solution

by:manojantony
manojantony earned 166 total points
ID: 12277497

in atoi there is no error tracking.. use strtol instead.
and strod for float/double
...........................
   int i; float f;
   char *word;
   char * string = "Hello,this,is,the,wor1d";
   char *token = ",\0\n";
   word = strtok(string, token)
   i = strtol(word, &perr,0);
   if (!pErr[0])
         intValue = i;
   else
         printf("Error");
   .........
   word = strtok(NULL, token)
   f = strtof(word, &perr);
   if (!pErr[0])
         floatValue = f;
   else
         printf("Error");                  
...............................

perr can be used for error catching !
0
 

Expert Comment

by:charukalanidhi
ID: 12672775
hi jakekula,

the easiest solution can be provided to you if you post a sample of your file.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question