Compose a capacity named arrayToFile . The capacity ought to acknowledge three contentions: the name of a record, a pointer to an int cluster, and the size of the exhibit. The capacity should open the predetermined document in twofold mode, compose the substance of the exhibit to the record, and afterward close the document.
Compose another capacity named fileToArray . This capacity ought to acknowledge three contentions: the name of a document, a pointer to an int cluster, and the size of the exhibit. The capacity should open the predefined record in parallel mode, read its substance into the cluster, and afterward close the document.
void arraytofile(string str, int *ptr, int size)
{
fstream file;
file.open("str", ios::out | ios::binary);
if(file.fail())
{
cout<<"file opening failed"<<endl;
}
int main()
{
int size=5;
int array[size]= {'1','2','3','4','5'};
int *intptr=NULL;
intptr=array;
string str;
cout<<"enter the name of the file"<<endl;
cin>>str;
arraytofile(str, intptr, size);
cout<<"data is written into file"<<endl;
int array2[size];
int *secptr=NULL;
secptr=array2;
filetoarray(str, secptr, size);
cout<<"data is in array"<<endl;
}
Edit & Run
You could also do with a better translator!
"compose" -> write
"capacity" -> function
"contention" -> argument
"cluster" -> array
"document" -> file
"exhibit" -> (no idea)
#include <iostream> // Please include your headers
#include <fstream>
usingnamespace std;
void arraytofile( string str, int *ptr, int size )
{
fstream file( str, ios::out | ios::binary ); // Don't put str in quotes: it is already a string
if ( !file )
{
cout << "File opening failed\n";
return; // So don't go any further with it
}
file.write( (char*)ptr, size * sizeof(int) ); // Write the lot in one go
} // fstream file closes automatically
void filetoarray( string str, int *ptr, int size )
{
fstream file( str, ios::in | ios::binary ); // Don't put str in quotes: it is already a string
if ( !file )
{
cout << "File is not opened\n";
return; // So don't go any further with it
}
file.read( (char *)ptr, size * sizeof(int) ); // Read the lot in one go
} // fstream file closes automatically
int main()
{
constint size = 5; // Need const here to size an array
int arr[size] = { 1, 2, 3, 4, 5 }; // Just numbers - no quotes
string str;
cout << "Enter the name of the file: ";
cin >> str;
arraytofile( str, arr, size ); // arr will decay to a pointer anyway
cout << "Data is written to file\n";
int arr2[size];
filetoarray( str, arr2, size );
cout << "Data is in array: ";
for ( int i = 0; i < size; i++ ) cout << arr2[i] << ' ';
}
Enter the name of the file: test.txt
Data is written to file
Data is in array: 1 2 3 4 5