[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

Structures and Reading in a file

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
jakekula
Asked:
jakekula
3 Solutions
 
lwinkenbCommented:
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
 
itsmeandnobodyelseCommented:
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
 
lwinkenbCommented:
This is the C forum Alex, not C++.
0
Free tool for managing users' photos in Office 365

Easily upload multiple users’ photos to Office 365. Manage them with an intuitive GUI and use handy built-in cropping and resizing options. Link photos with users based on Azure AD attributes. Free tool!

 
itsmeandnobodyelseCommented:
@lwinkenb: Thanks. My fault. I opened the wrong directory.

@jakekula: I'll convert it to C

Regards, Alex



0
 
itsmeandnobodyelseCommented:
// 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
 
ankuratvbCommented:
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
 
aravindtjCommented:
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
 
manojantonyCommented:

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
 
charukalanidhiCommented:
hi jakekula,

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

Featured Post

Will You Be GDPR Compliant by 5/28/2018?

GDPR? That's a regulation for the European Union. But, if you collect data from customers or employees within the EU, then you need to know about GDPR and make sure your organization is compliant by May 2018. Check out our preparation checklist to make sure you're on track today!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now