Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Structures and Reading in a file

Posted on 2004-10-05
12
Medium Priority
?
375 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 672 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 664 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 664 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
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 pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

704 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