C++ Read txt file and append data in each line - c++

I want to open a file, and in each line append a string in the end.
I have this code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//argv[1] input file
//argv[2] string to add in the end of each line
//argv[3] output file
int main(int argc, char *argv[]){
ifstream open_file(argv[1]);
if (!open_file) {
std::cerr << "Could not open input file\n";
return 0;
}
ofstream new_file(argv[3]);
if (!new_file) {
std::cerr << "Could not create output file\n";
return 0;
}
string s = argv[2];
string str;
while (getline(open_file, str)) {
new_file << str << s << "\n";
}
}
The thing is the string is not adding in the end of each line. It is creating a new line for each string trying to be appended.
So I run for example: ./appendstring.e wordlist.txt hello new_wordlist.txt
and this is the output:
I don't really know what I'm doing wrong here.
Thanks in advance.

Perhaps your first file contains \r\n sequences for End of Line..
You may have to remove the \r character that is already in your first file, because you are reading in the string with the \r on the end.
Trim the \r off the end of str, before you use this line of code:
new_file << str << s << "\n";
See here
http://www.cplusplus.com/reference/string/string/getline/

Related

c++ how to remove/replace the last line of a file?

How do I remove/replace the last line of a file in C++? I looked at these questions:
Deleting specific line from file, Read and remove first (or last) line from txt file without copying
. I thought about iterating to the end of the file and then replacing the last line but I'm not sure how to do that.
Find the position of the last occurrence of '\n' in the file content. If the file ends with '\n', i.e there is no more data after the last '\n', then find the position of the previous occurrence of '\n'. Use resize_file to truncate files at the found position or just replace the content after the found position.
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
if (fin.eof()) {
fout << "text to replace last line";
} else {
fout << buffer << '\n';
}
}
fin.close();
fout.close();
}
Also you can read and store all your input file, modify and then write it:
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
// read
ifstream fin("input.txt");
vector<string> lines;
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
lines.push_back(buffer + '\n');
}
fin.close();
// modify
lines[lines.size() - 1] = "text to replace last line";
// write
ofstream fout("output.txt");
for (string line: lines) { // c++11 syntax
fout << line;
}
fout.close();
}

C++ Outputting a text file in reverse order [duplicate]

This question already has answers here:
How to read a file in reverse order using C++ [duplicate]
(3 answers)
Closed 5 years ago.
For this program I am writing, I am suppose to be taking in a text file from the command line, reversing the order of everything in the file and then outputting the text into a new text file with "-reverse" attached on to it. The problem I am having is reversing the order of the lines. I've been able to reverse the text but I need help reversing the lines. I've seen suggestions about using vectors but I'm still new to c++ and I believe i'm not suppose to be using vectors just high-level io
For example, filename.txt contains:
abc
edf
dfg
filename-reverse.txt should contain:
gfd
fde
cba
Mine only contains:
cba
fde
gfd
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Reverses the line
*/
void reverseStr(string& x)
{
reverse(x.begin(), x.end());
}
int main(int argc, char *argv[])
{
string filename = argv[1];
string filenameCopy = filename;
string reverse = "-reverse";
string reverseFileName;
string reverseLine;
if(filename.rfind(".txt"))//inserts -reverse into existing file name
{
reverseFileName = filenameCopy.insert(filenameCopy.length() - 4,reverse);
}
string line;
ifstream myfile (filename);
ofstream out(reverseFileName);
if (myfile.is_open())
{
/*
vector<string> lines_in_reverse;
while(getline(myfile,line))
{
lines_in_reverse.insert(lines_in_reverse.begin(), line);
}
*/
while(getline(myfile,line))
{
cout << line << endl;
reverseStr(line);
cout << line << endl;
out << line << endl;
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
return EXIT_SUCCESS;
}//main
Simple to do; just read the entire file into a std::string, then iterate over the string in reverse order (from rbegin() to rend()) and print each character as you go along.

Search words in line of an external file in c++

I have the following problem:
I have a text file file.txt which contains several lines in which I want to search for specific words. The words I want to search for are in a second file input.txt, which may look like this:
Paul
Matt
Joseph
In the first loop I want to search for Paul, in the second for Matt and in the third for Joseph. Each time I find the specific name in a line of the text file, I want to output the line and keep on searching through all following lines of the text file.
Currently my code looks like this:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream fs("input.txt");
ifstream stream1("file.txt");
ofstream stream2("output.txt");
string Name;
string line;
while (fs >> Name)
{
while (std::getline(stream1, line))
{
if ((line.find(Name) != string::npos))
{
stream2 << Name << line << endl;
}
else
stream2 << "Unable to find name in line" << endl;;
}
}
fs.close();
stream1.close();
stream2.close();
return EXIT_SUCCESS;
}
The problem with my code is that it searches for the first word fine, but it stops after the first loop. It does not search for the second word ("e.g. Matt").
Maybe someone has an idea what I have made for a mistake.
Thanks a lot :-)
When you open input.txt then read all elements from this file when name = Paul. After read all, cursor will be stand at the end of file input.txt. That's why, when you again search for Matt, You can't find anything.
So, you should always start search from the input.txt. So, you can do that for open this file then cursor will be stand first.
Just simple change:
while (fs >> Name)
{
ifstream stream1("file.txt");
while (std::getline(stream1, line))
{
if ((line.find(Name) != string::npos))
{
stream2 << Name << line << endl;
}
else
stream2 << "Unable to find name in line" << endl;;
}
stream1.close();
}
Once the inner loop is done, you're at the end of the file for stream1. You need to "rewind" the read position to the beginning. This can be done by seeking to the first position.

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

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