Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a string to the end of a file (C++)

Tags:

I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++)

 void main() {    std::string str = "I am here";    fileOUT << str; } 

I realize there is much to be added to this and I do apologize if it seems I am asking people to code for me, but I am completely lost because I have never done this type of programming before.

I have attempted different methods that I have come across the internet, but this is the closest thing that works and is somewhat familiar.

like image 363
ked Avatar asked Aug 03 '11 19:08

ked


People also ask

How to write at end of file in C?

Step 1: Open file in write mode. Step 2: Until character reaches end of the file, write each character in filepointer. Step 3: Close file.

How to write to a file using C?

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

How to open a file using C?

To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file. FILE * fopen ( const char *filename, const char *mode);


2 Answers

Open your file using std::ios::app

 #include <fstream>   std::ofstream out;   // std::ios::app is the open mode "append" meaning  // new data will be written to the end of the file.  out.open("myfile.txt", std::ios::app);   std::string str = "I am here.";  out << str; 
like image 183
Chad Avatar answered Oct 20 '22 03:10

Chad


To append contents to the end of files, simply open a file with ofstream (which stands for out file stream) in app mode (which stands for append).

#include <fstream> using namespace std;  int main() {     ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode      fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file      fileOUT.close(); // close the file     return 0; } 
like image 34
Seth Carnegie Avatar answered Oct 20 '22 04:10

Seth Carnegie