These are my examples:
/*int WriteFile(const char* file_name)
{
fstream file;
try
{
file.open(file_name,ios.out);
file << "67";
//file << "I miss you very much.";
file.close();
}
catch(exception& e)
{
cout << e.what();
return 1;
}
return 0;
}*/
/*int ReadFile(const char* file_name)
{
fstream file;
file.open(file_name,ios.in);
if(file.is_open())
{
string data;
while(!file.eof())
{
getline(file,data,cin.widen('\n'));
cout << data << '\n';
}
file.close();
}
else
{
cout << "Unable to open file!\n";
return 1;
}
return 0;
}*/
int ReadFile(const char* file_name)
{
fstream file(file_name,ios.in|ios.binary|ios.ate);
if(file.is_open())
{
fstream::pos_type size=file.tellg();
char* data_block=new char[int(size)+1];
file.seekg(0,ios.beg);
file.read(data_block,size);
data_block[size]=0;
file.close();
cout << data_block << "(" << size << ")" << "\n";
cout << "Read file successfully!\n";
delete []data_block;
}
else
{
cout << "Unable to open file!\n";
return 1;
}
return 0;
}
int WriteFile(const char* file_name)
{
fstream file(file_name,ios.out|ios.binary);
if(file.is_open())
{
string data_block="I know I succeed!";
file.write(data_block.c_str(),data_block.length());
file.close();
cout << data_block << "(" << data_block.length() << ")" << "\n";
cout << "Write file successfully!\n";
}
else
{
cout << "Unable to open file!\n";
return 1;
}
return 0;
}
int ObtainFileSize(const char* file_name)
{
fstream file(file_name,ios.in);
if(file.is_open())
{
int begin, end;
begin=file.tellg();
file.seekg(begin,ios.end);
end=file.tellg();
file.close();
//cout << begin << "\n";
//cout << end << "\n";
return end-begin;
}
else
{
cout << "Unable to open file!\n";
return -1;
}
}
int main()
{
/*string str;
cout << "Enter file name: ";
getline (cin,str,cin.widen('\n'));
char* file_name=new (nothrow) char[str.length()+1];
if(file_name==0)
{
cout << "Error: Memory could not be allocated!\n";
}
else
{
strcpy(file_name,str.c_str());
WriteFile(file_name);
ReadFile(file_name);
delete[] file_name;
}*/
string file_name;
cout << "Enter file name: ";
getline (cin,file_name);
WriteFile(file_name.c_str());
ReadFile(file_name.c_str());
if(ObtainFileSize(file_name.c_str())>=0)
{
cout << "File size is " << ObtainFileSize(file_name.c_str()) << " bytes\n";
}
getch();
return 0;
}