Jump to content

  • Log In with Google      Sign In   
  • Create Account





C++ File Read Write Save Delete Example

Posted by Shippou, 03 March 2014 · 496 views

C++ file i/o io
A simplified example of how to work with files in C++ .
.
// Create File, Write To File
// Close File
// Open File, Dump Text To Aray
// Close File
// Delete File
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string str[1];
  ofstream a_file ("Ftest.txt");
  a_file<<"File Test";
  a_file.close();
string line[1];
  ifstream b_file ("Ftest.txt");
  if (b_file.is_open())
  {   
      getline (b_file,line[0]);
      cout << line << endl;
      b_file.close();
      remove("Ftest.txt");
  }}
      





It'd be simpler still if there weren't one-element arrays, which are confusing to someone that thinks they're there for a reason.

Moreover, str seems to go unused.

With respect, that is a dreadful example:

 

1) As has been pointed out, you are using arrays of variables pointlessly - a simple variable will suffice

2) You aren't including the correct header for "remove" (cstdlib I think, or maybe cstdio)

3) Your comments are misleading - nowhere do I see an array (Aray) being used

4) You aren't checking error states anywhere - this is important with files

 

I'll be nice and blame the terrible formatting on GDNet's code editor.

PARTNERS