C++ a simple example of writing and reading files safely and concisely

  • 2020-05-24 05:56:54
  • OfStack

C++ a simple example of writing and reading files safely and concisely

Example code:


#include <string> 
#include <iostream> 
#include <fstream> 
 
using namespace std; 
 
int get_file_content(string sFileName, string& sFileContent); 
 
int main(int argc, char* argv[]) 
{ 
  string sFileContent; 
  get_file_content("./test", sFileContent); 
  cout << sFileContent << endl; 
  return 0; 
}  
 
int get_file_content(string sFileName, string& sFileContent) 
{ 
  ifstream ifs (sFileName.c_str(), ifstream::in); 
 
  sFileContent.clear(); 
  char c; 
    while (ifs.get(c)){ 
    sFileContent.append(1, c); 
  } 
 
  ifs.close(); 
 
  return 0; 
} 
 
int set_file_content(string sFileName, string& sFileContent) 
{ 
  ofstream ofs(sFileName.c_str(), ofstream::binary); 
  size_t nCount = sFileContent.size(); 
  ofs.write (sFileContent.c_str(), nCount); 
  
  ofs.close(); 
 
  return nCount; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: