How to append text to a text file in C++?
Mia Lopez
How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.
16 Answers
You need to specify the append open mode like
#include <fstream>
int main() { std::ofstream outfile; outfile.open("test.txt", std::ios_base::app); // append instead of overwrite outfile << "Data"; return 0;
} 6 I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.
static void appendLineToFile(string filepath, string line)
{ std::ofstream file; //can't enable exception now because of gcc bug that raises ios_base::failure with useless message //file.exceptions(file.exceptions() | std::ios::failbit); file.open(filepath, std::ios::out | std::ios::app); if (file.fail()) throw std::ios_base::failure(std::strerror(errno)); //make sure write fails with exception if something is wrong file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit); file << line << std::endl;
} #include <fstream> #include <iostream> FILE * pFileTXT; int counter
int main()
{ pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted for(counter=0;counter<9;counter++) fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file fprintf(pFileTXT,"\n");// newline for(counter=0;counter<9;counter++) fprintf (pFileTXT, "%d", digitarray[counter] ); // numerical to file fprintf(pFileTXT,"A Sentence"); // String to file fprintf (pFileXML,"%.2x",character); // Printing hex value, 0x31 if character= 1 fclose (pFileTXT); // must close after opening return 0;
} 4 You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...You can find more information about the open modes here and about fstreams here.
You could also do it like this
#include <fstream>
int main(){
std::ofstream ost {outputfile, std::ios_base::app};
ost.open(outputfile);
ost << "something you want to add to your outputfile";
ost.close();
return 0;
} 2 The code below should work:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{ ofstream writer("filename.file-extension" , ios::app); if (!writer) { cout << "Error Opening File" << endl; return -1; } string info = ""; //insert your text to be appended here writer.append(info); writer << info << endl; writer.close; return 0;
} I hope this helps you :)
1