简体   繁体   中英

creating and reading/writing to files with fstream in C++

I'm looking to create a file, then open it and rewrite to it.

I've found I can create a file by simply doing this:

#include <iostream>
#include <fstream>  
using namespace std;
int main()
{
ofstream outfile ("test.txt");
outfile << "my text here!" << endl;
outfile.close();
return 0;
}

while this works to create the test file, I cannot open the file and then edit it. this (below) does not work even after the file is created.

outfile.open("test.txt", ios::out);
if (outfile.is_open())
{
    outfile << "write this to the file";
}
else
    cout << "File could not be opened";
outfile.close;

If by "does not work" you mean that the text is overwritten instead of appended, you need to specify std::ios::app as one of the flags to the call to open to have it append more data instead of overwriting everything.

outfile.open("test.txt", ios::out | ios::app);

The following example works fine for me:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  ofstream outfile ("test.txt");
  outfile << "my text here!" << endl;
  outfile.close();

  outfile.open("test.txt", ios::out | ios::app );
  if (outfile.is_open())
     outfile << "write this to the file" << endl;
  else
     cout << "File could not be opened";

  outfile.close();

  return 0;
}

Produces the following text file:

my text here!
write this to the file

You can also do that with FOPEN. Some compilers will notice you that the function its OBSOLETE or DEPRECATED but for me its working good.

/* fopen example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ("myfile.txt","w");
  if (pFile!=NULL)
  {
    fputs ("fopen example",pFile);
    fclose (pFile);
  }
  return 0;
}

More info here: http://www.cplusplus.com/reference/cstdio/fopen/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM