I have a file of data that was put into a data file by another program with the same struct. for this program i want to take that data out of the .txt file and put it back into the struct array. is there any big code that is wrong that is popping out? i keep getting a segmentation fault during the while loop in the build array function. any ideas why? or any code that would lead to this? (i know i could probably use some more advanced code but this is all i have to work with from class)

if anything, is it correct how i am laying stuff out in the build arrays function?

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std; 

const int num = 36;

struct teamInfo
{
       char schoolName[20];
       char teamName[20];
       int game1score;
       int game2score;
       int game3score;
};

//Function prototype
int buildArray( teamInfo teamAr[] );



int main()               
{      
   //Declarations 
   int numTeams;
   teamInfo teamAr[num];    //array of structs


            
      numTeams = buildArray(teamAr);
      displayArray(teamAr, numTeams);


   
  system("pause");     
  return 0;
  
}


***********************************************/
int buildArray( teamInfo teamAr[] )
{
    
    ifstream inFile;
    ofstream outFile;
    
         
   inFile.open("results.txt", ios::binary);
  
   //test if input file opened correctly
   if (inFile.fail() )
   {
   cout << "input file did not open";     
   }

   int i = 0;
   
   inFile.read( (char *) &teamAr, sizeof(teamAr) );  //primary read
   while(inFile)
   {
   inFile.read( (char *) &teamAr[i], sizeof(teamAr) );     
   i++; //increments to next spot in array
   }
  
    inFile.close();
    return (i);   
         
}

Edited 7 Years Ago by __avd: Add [code] tags. Encase your code in: [code] and [/code] tags.

scroll down..

|
|
|
\ /
\ /
\ /
\/

Edited 7 Years Ago by Clinton Portis: I have a fever, and there's only one prescription...

How is the file written out?
e.g. struct1.member1
struct1.member2
struct2.member1
struct2.member2

I don't think you can read it in with read() that's for char* (I see what you were trying to do with your casting). You may have to read it in member by member (if you know the order ahead of time which is why I asked that question before). Use an ifstream and go myifstream>>structure.member and as long as the types are correct it should work (do any error checking you deem necessary).

actually i figured out the problem: where i have:
inFile.read( (char *) &teamAr, sizeof(teamAr)

i needed to change it to

inFile.read( (char *) &teamAr, sizeof(teamInfo)

now it works and i can output the members

This article has been dead for over six months. Start a new discussion instead.