Solved

Structures and Reading in a file

Posted on 2004-10-05
12
364 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
Comment Utility
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
Comment Utility
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
Comment Utility
This is the C forum Alex, not C++.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
@lwinkenb: Thanks. My fault. I opened the wrong directory.

@jakekula: I'll convert it to C

Regards, Alex



0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 168 total points
Comment Utility
// 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
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
hi jakekula,

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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

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…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

763 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now