reading a data file with spaces

I need to read a data file with spaces. The data file size in not set so I need to load data in a memory space and then read each string ending with null and compare all the characters to compute the min, max and sum. I already used fstream to get the size of the file but my problem is to read each data because each data contain a space and two number and end with a space. In the data file, each integer is formatted as “ ##”, where it starts with blank space and two digit numbers Any help will be appreciated.

This is where i am at:

#define BUF_SIZE 3 //Every number takes 3 bytes on data.

using namespace std;

struct DATA
{
int *pData;
int nSize;
int nSum;
int nMax;
int nMin;
float fMean;
};

struct DATA ReadDataFile(const char *pFileName);

int main(void)
{
// ReadDataFile reads "data.dat" file and// set the information into szData.

DATA stData = ReadDataFile ("data.txt"); // Display all data of szData
for (int i = 0; i < stData.nSize; i++)
std::cout << *(stData.pData + i) << " ";
std::cout << "\nWe read " << stData.nSize << " numbers of data\n";
std::c
out << "MAX: " << stData.nMax << "\n" << "MIN: " << stData.nMin;

getchar();
return 0;
}

struct DATA ReadDataFile(const char *pFilename)
{
FILE *pFile;
char *szBuf;
int nSize;

pFile = fopen("data.txt", "r");
if (pFile == NULL) // if there is no data.txt,
{
printf("The file does not exist");
exit(1); // exits, which means there is an error while the program executes.
}

while (1)
{
//Obtains the size of the file
fseek (pFile , 0 , SEEK_END);
int fSize = ftell (pFile);
rewind (pFile);

//Allocate the memory space to contain the whole file
szBuf = (char*) malloc (sizeof(char)*fSize);
if (szBuf == NULL) {fputs ("Memory error",stderr); exit (2);}


//Read the whole file
nSize = fread (szBuf,BUF_SIZE,fSize,pFile);
szBuf[nSize = NULL;
//printf("%s", szBuf);
//printf("%d", nSize);
if (!fread(szBuf,BUF_SIZE,fSize,pFile))
break;
//szBuf[BUF_SIZE + 1];

//szBuf[4] = 0;
printf("%d\n", atoi(szBuf));

//Assign null at the end to make it a string
//printf("%d", atoi(szBuf));//Convert a string to a number

int nMin;
int nMax;
int nSum = 0;
float fMean;

for (int i = 0; i < nSize; i++)
{
nMax = szBuf[i];
nMin = szBuf[i];
if (szBuf[i] > nMax)
nMax = szBuf[i];
if (szBuf[i] < nMin)
nMin = szBuf[i];

nSum = szBuf[i] + nSum;
}

fMean = nSum / nSize;

fclose(pFile);
getchar();

}
}


Topic archived. No new replies allowed.