fstream c ++ functions return full line fstream - c++

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;
}

Related

Put a custom string into a file

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;
}

How to read from an input stream into a file stream?

I am trying to bind input stream with a file stream , I hope that input something from input stream and then automatic flush to the file stream
It does not work...I enter something from keyboard , outfile is still empty
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile)
throw runtime_error("Open the file error");
ostream * old_tie = cin.tie();//get old tie
cin.tie(0);//unbind from old tie
cin.tie(&outfile);//bind new ostream
string temp;
while(cin >> temp)
{
if(temp == ".")//stop input
break;
}
cin.tie(0);
cin.tie(old_tie);// recovery old tie
return 0;
}
Your program is too complicated and is misusing tie(). Try the following:
#include <iostream>
#include <fstream>
int main() {
using namespace std;
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile) {
cerr << "Open the file error";
return 1;
}
char data(0);
while(data != '.') {
cin.get(data);
cin.clear(); // Prevents EOF errors;
outfile << data;
}
return 0;
}
It reads char by char until it finds a .
Errors:
why make throw exception if you don't catch it...
close file please
do you put data from file to temp and go through it to find "." and
end program?
Why do you use pointer for old_tie use it for the first ofstream file
like this ofstream * file.
fix if statement and break
include string library -- //This might solve your problem
what is filename??
is tie(0) function to unbind?
//EDIT
Explanation:
once you find first period with find_first_of function you create a substr and copy it into outfile. The Solution is so efficent and works every time. The logic is as simple as it can get. Don't use unnecessary functions and initialize unnecessary variables because it is more complex and more prone to errors when you have too many variables.
Solution: - No need for cin.tie()
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
string s;
getline(cin, s);
int i = s.find_first_of(".");
if(i!=std::string::npos)
{
s = s.substr(0, i);
outfile << s;
}
else
{
cout << "No periods found" << endl;
}
}
Compiled code - http://ideone.com/ooj1ej
If this needs explanation please ask questions in comments below.

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)

How to read a file line by line or a whole text file at once?

I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error

C++ How do i check for delimiter in this text file

i am new to C++. I would like to know how do i create a function to check for delimiter.
such as the case below
AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00
AE,United Arab Emirates,AE,AE,ARE,784.00,Abu Dhabi,Middle East,UAE Dirham,AED,2407460.00
AF,Afghanistan,AF,AF,AFG,4.00,Kabul,Asia,Afghani,AFA,26813057.00
If the delimiter become $ or # instead of comma , how do i create a function to check for it and say , wrong format of text file.
Thanks!
Below is my readData code
void readData ()
{
FILE * pFile;
NoOfRecordsRead = 0;
char buffer [Line_Char_Buffer_Size];
pFile = fopen (INPUT_FILE_NAME , "r");
if (pFile == NULL)
perror ("Error opening file 'Countries.txt' !");
else
{
while ( !feof (pFile) )
{
char* aLine = get_line (buffer, Line_Char_Buffer_Size, pFile);
if (aLine != NULL)
{
// printf ("%d] aLine => %s\n", NoOfRecordsRead, aLine);
globalCountryDataArray [NoOfRecordsRead++] = createCountryRecord (aLine);
}
}
fclose (pFile);
}
}
#include <string>
#include <fstream>
#include <algorithm>
bool detect_comma(std::string file_name)
{
// open C++ stream to file
std::ifstream file(file_name.c_str());
// file not opened, return false
if(!file.is_open()) return false;
// read a line from the file
std::string wtf;
std::istream &in= std::getline(file, wtf);
// unable to read the line, return false
if(!in) return false;
// try to find a comma, return true if comma is found within the string
return std::find(wtf.begin(), wtf.end(), ',')!= wtf.end();
}
#include <iostream>
#include <cstdlib>
int main()
{
if(!detect_comma("yourfile.dat"))
{
std::cerr<< "File is not comma delimited!\n";
return EXIT_FAILURE;
}
// file is OK, open it and start reading
}
Edit: Added comments & example code
You would need a reliable way to find a location that you always expect the delimiter to be. If the first field is always 2 characters wide, you can check to see if the 3rd character is a ,. Otherwise, you can scan backwards on the first line of text to see if the first non-currency related character is a ,.
Edit: Your readData routine is very C-centric, as has been pointed out in comments. You can simplify it considerably by using C++ features.
std::string aLine;
std::ifstream pfile(INPUT_FILE_NAME);
while (pfile) {
std::getline(pfile, aLine);
if (aLine.size()) {
globalCountryDataArray.push_back(createCountryRecord(aLine));
}
}
A good way to perform your check is using the Boost.Regex library. You only have to define your regular expression and perform a check if your input matches the expression.
Sample code:
#include <string>
#include <boost/regex.hpp>
using namespace std;
int main()
{
const string input("AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00");
const boost::regex ex("(?:(?!,)(\\d+\\.\\d*)|(\\w|\\s)*)(,(?:(?!,)(\\d+\\.\\d*)|(\\w|\\s)*))*");
cout << boost::regex_match(input.c_str(), ex) << endl;
return 0;
}
By the way: I'm not a regex expert so validate the expression :-)