Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Program 1

Program to read dynamic data from file


#include<iostream>
#include<fstream>
using namespace std;
int calculate_fileSize(char*); // will receive the file name
int* dynamic_memory(int); // this will return the memory
allocation according to memory read from hard dis file
void read_file(int*, char*,int);
void diplay_array(int*, int);
int main()
{

char fname[20] = "mydata.txt";


int* receiving_array;
int count = 0;
count = calculate_fileSize(fname);
//int* receiving_array;
receiving_array= dynamic_memory(count);
cout << "-----------------------" << count << endl;
read_file(receiving_array, fname, count);
diplay_array(receiving_array,count);

system("pause");
return 0;

}//end of main
void diplay_array(int* aptr, int s)
{
for (int i = 0; i < s;i++)
{
cout << aptr[i] << endl;
}
}
void read_file(int* myarray, char* fn, int fsize)
{
ifstream fin;
fin.open(fn);
for (int i = 0; i < fsize; i++)
{
fin>> myarray[i];
}

}
int calculate_fileSize(char* fname)
{
fstream fin;
int c = 0;
int temp; //this temporary variable declared will
accept /recieve the array elements one by one
fin.open(fname);
while (fin>>temp)
{
c++;
}
return c;

}// end of calculate_fileSize()

int* dynamic_memory(int size)


{
int* temp = NULL;
temp = new int[size];
return temp;
}
Program 2
Regrow 1D Array
#include<iostream>
#include<fstream>
using namespace std;
void copyArray(int* newarray, int* oldarray, int s);
int* Regrow1D(int* oldarray, int s, int value);
void diplay_array(int*, int);

int main()
{
char filename[20] = "mydata.txt";
int* data = NULL;
int size = 0;
int num = 0;
ifstream fin;
fin.open(filename);
fin >> num;
data = new int[1]; //one memory cell of 4 bytes
resereve
data[0] = num;
cout << "------------------ : " << data[0] << endl;
size++; // first memory cell is gain so increase
the size of new created arrray
while (fin >> num)
{
data = Regrow1D(data,size,num);
size++;
}

//cout << "before calling display_array() inside


size variable is: " << size << endl;
diplay_array(data, size);
system("pause");
return 0;

}//end of main
void copyArray(int* newarray,int* oldarray,int s)
{
for (int i = 0; i < s;i++)
{
newarray[i] = oldarray[i];
}//end of for
}

int* Regrow1D(int* oldarray,int s,int value)


{
int* newarray = NULL;
newarray = new int[s + 1];
copyArray(newarray, oldarray, s);
newarray[s] = value;
delete[] oldarray;
return newarray;

void diplay_array(int* aptr, int s)


{
for (int i = 0; i < s;i++)
{

cout << aptr[i] << endl;


}

You might also like