Put a custom string into a file - c++

I want to add a new line (string) into the end of an existing file. But it didn't work. Here is the code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
ifstream input("Sample.ini");
ofstream output("Sample.ini",ios::app);
cout << "Lines that have existed in file:" << endl;
while (input) // Print out the existed line
{
string newstring;
getline(input,newstring);
cout << newstring << endl;
}
cout << "Line you want to add:" << endl;
string outputstring;
getline(outputstring,output); // get the whole line of outputstring,
// and deliver it into output file
return 0;
}
The first getline which reads lines inside the file to a string works well. But, the second one, is not.
The compiler returned like this:
...\file test.cpp|35|error: no matching function for call to 'getline(std::istream&, std::ofstream&)'|

You wrote too much code. You need two lines only:
ofstream output("Sample.ini",ios::app);
output << outputstring;

you may want to try poniter to file, short & simple
#include <stdio.h>
int main ()
{
FILE * pFile;
File = fopen ( "you_file_name.txt" , "a" ); //open the file in append mode
fputs ( "This is an apple." , pFile );
fseek ( pFile , 0 , SEEK_END); // 0 means from start & SEEK_END will get you the end of file
fputs ( "Line you want to add:" , pFile );
fclose ( pFile );
return 0;
}

Related

fstream c ++ functions return full line fstream

C ++ language for the creation of a personal web, here I use C++ as cgi to output to a web server XAMP, with load fstream to separate manuscript with c ++ html, making htmlstream function as pieces that are not too complicated in notepad while coding c ++, the problem is when a function htmlstream made, only one line of text, it can not display all the text
#include <iostream>
#include <fstream>
using namespace std;
string htmlstream(const char* _filename){
string htmltext;
fstream open_html (_filename);
if(open_html.is_open()){
while(getline(open_html,htmltext)){
return htmltext;
}
}else{
cout<<"File: NO Reading"<<endl;
}
}
int main(){
string importhtml = htmlstream("body.html");
cout<<importhtml;
return 0;
}
The reason why one line of text is only display is because the function getline reads until it reaches the end of the current line. That is, every time a line is read, the value of the string variable is changed.
If storing the value of each line is what you want, then you will have to append every line as you read. There are multiple solutions, I decided to go with something simple.
See if this helps.
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
/// Simplify calls to the standard library
using namespace std;
string htmlStream( const char *fileName )
{
string text; /// Content of current file
ifstream inFile; /// Input file stream
inFile.open( fileName ); /// Open file to read
if ( inFile.is_open() ) {
/// File successfully open, so process it
string line; /// String being read
/// Read file, line by line
while ( getline( inFile, line ) ) {
text += line;
}
}
else {
/// Could not open file, so report error to the stderr
cerr << "Cannot open \"" << fileName << "\"" << endl;
exit( EXIT_FAILURE );
}
return text;
}
int main( int argc, const char * argv[] ) {
string str = htmlStream( "darkness.txt" );
cout << str << endl;
return EXIT_SUCCESS;
}

fstream to display all text in txt

I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)

Simple File-I/O Program C++

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}

C++ Read and modify a line in a txt file

I'm facing some difficulties with the searching of the position of the first occurrence of a word.
The software have to search into a determined txt file a specified word. So I've used the fstream lib to open and after all write something. But I have no clue how I will make the software to get the exactly position of the that word. All I got is this:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main() {
fstream myfile; // fstream to read and write the myfile
string cText = "\n--something--!\n"; // what it will write
string line; // will assign the getline() value;
unsigned int pos = 0; //will be assigned to "seekp" - where it will start to write
myfile.open( "example.html", ios::binary | ios::in | ios::out );
if( !myfile ) {
cout << "File does not exist!" << endl;
cin.get();
return false;
}
do {
size_t found = line.find("<head>");
cout << string::npos << endl;
if (found != string::npos) {
cout << line << endl;
}
}while( getline(myfile, line));
myfile.seekp( pos+1, ios::beg );
//myfile.write( cText, strlen( cText ) ); //write cText
myfile.close();
cin.get();
return 0;
}
Any suggestions?
Don't try to change the bytes in your file. Make a new file, copy the lines over until you find the one you want to replace, output your new line, then output the rest of your lines. Because unless you're replacing one string, with another string with exactly the same number of characters, you're going to be overriding the next line in your file - and there's no good way to avoid that.
If you want to, you can then delete the original file, and rename your new file to that name.

Problems using seekg in C++

I'm reading a file through a function like this:
#include <iostream>
#include <fstream>
#include <string>
...
void readfile(string name){
string line;
int p = 0;
ifstream f(name.c_str());
while(getline(f,line)){
p++;
}
f.seekg(0);
cout << p << endl;
getline(f,line);
cout << line << endl;
}
Mi file has 3 lines:
first
second
third
I expected the output:
3
first
Instead I get:
3
(nothing)
why is my seekg not working?
Because seekg() fails if the stream has reached the end of the file (eofbit is set), which occurs due to your getline looping. As sftrabbit implies, calling clear() will reset that bit and should allow you to seek properly. (Or you could just use C++11, in which seekg will clear eofbit itself.)
Use iterators for read from the file
std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
std::istreambuf_iterator<char>( file ),
std::istreambuf_iterator<char>() );