reading an entire txt file to memory

how would I read an entire txt file to memory at 1 shot? and how would I know the amount of memory to reserve to store the data, etc?
Last edited on
Create a txt file with the information in correct columns, as if you don't the information won't be right. This code should help.

ifstream inputFile;
ofstream outputFile;
inputFile.open("payInput.txt");
outputFile.open("outputFile.txt");

if(inputFile.fail())
cout << "Error opening inputfile!\n";
else if(outputFile.fail())
cout << "Error opening outputfile!\n";
else
{
outputColHeadings(outputFile);
readFileValues(inputFile, empIDArray, rateArray, hoursArray, dependArray);
then do calculations....
------FUNCTIONS--------------
void outputColHeadings(ofstream& outputFile)
{
outputFile <<" EmpId" << setw(10) <<"Rate"<< setw(9) <<"Hours" << setw(6)
<<"Dep" << setw(12) <<"Gross Pay" << setw(11) << "Fed. Tax"
<< setw(12) <<"State Tax" << setw(12) <<"Net Pay\n";
for (int i = 1; i <= 78; i++)
outputFile << "=";
outputFile << "\n";

return;
}//outputColHeadings
void readFileValues(ifstream& inputFile, long empID1Array[],
double rate1Array[], double hours1Array[],
int depend1Array[])
{
int i;

for(i=0; i < SIZE; i++)
inputFile >> empID1Array[i] >> rate1Array[i] >> hours1Array[i]
>> depend1Array[i];
return;
}//readFileValues

Hope that helped!
for(i=0; i < SIZE; i++)
inputFile >> empID1Array[i] >> rate1Array[i] >> hours1Array[i]
>> depend1Array[i];
return;
}//readFileValues


In this scenario, you still need to know how many records there are in the file as in the SIZE constant. what I want is to be able to read everything without needing to know the file size/how many records in advance. I assume that a dynamic data structure must be used in this case?
Last edited on
At least on Unix you can use stat or fstat function to get size of the file
Topic archived. No new replies allowed.