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

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.

Related

How to read total file line by line and set value to string [duplicate]

This question already has answers here:
Read whole ASCII file into C++ std::string [duplicate]
(9 answers)
How do I read an entire file into a std::string in C++?
(23 answers)
Closed 8 months ago.
I would like to read and display the content of a file entered by user at run-time
My code :
#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
int main()
{
char fileName[30], ch;
fstream fp;
cout<<"Enter the Name of File: ";
gets(fileName);
fp.open(fileName, fstream::in);
if(!fp)
{
cout<<"\nError Occurred!";
return 0;
}
cout<<"\nContent of "<<fileName<<":-\n";
while(fp>>noskipws>>ch)
cout<<ch;
fp.close();
cout<<endl;
return 0;
}
output :
C:\Users\prade\Desktop>g++ -o file file.cpp&file.exe
Enter the Name of File: tt.txt
Content of tt.txt:-
Hello , I am c++.
I am from us.
I am a programmer.
C:\Users\prade\Desktop>
I want to set the content of file to value of string str. I want to print the whole file's content by using cout<<str;
How can I do that ?
If you need to read the whole content of a text file into a std::string, you can use the code below.
The function ReadTextFile uses std::ifstream ::rdbuf to extract the content of the file into a std::stringstream. Then it uses std::stringstream::str to convert into a std::string.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
bool ReadTextFile(std::string const & fileName, std::string & text)
{
std::stringstream strStream;
std::ifstream fileStream(fileName);
if (!fileStream.is_open())
{
return false;
}
strStream << fileStream.rdbuf();
fileStream.close();
text = strStream.str();
return true;
}
int main()
{
std::string text;
if (!ReadTextFile("t.txt", text))
{
std::cout << "failed" << std::endl;
return 1;
}
std::cout << text << std::endl;
return 0;
}
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
Instead of extracting a single character from stream, you get extract a complete line using getline(). Your while loop should be something like this:
std::string line, contents;
while(getline(fp, line)) {
contents += line;
contents += "\n";
}
std::cout << contents;
Note that the above method is not efficient.

In C++, opening a csv file with ifstream

I am trying to open a csv file in C++ using ifstream with a directory in the file path name. The file does reside in the specified directory location, but I observe an for the variable inFile when executing the code. My research up to this point says the code is correct, but something obviously is wrong. Any suggestions?
Thanks,
KG
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open("csvFile", ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
I found the answer to my csv file opening problem, a colleague assisted.
#David - You suggested removing the double quotes in the "inFile.open" line of code. In addition to removing the double quotes, I also needed to add c_str(), which "returns a pointer to a null-terminated character array with data equivalent to those stored in the string," .data() also performs the same function (cppreference.com).
#user4581301 - I am also aware that ios::in is implied with a ifstream, only included it here as a reference; thanks.
The modified code is listed below:
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open(csvFile.c_str(), ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
Really appreciate all the help.
Enjoy,
KG
Is this what you're trying to do?
#include <iostream> // std::{ cout, endl }
#include <string> // std::{ string, getline }
#include <fstream> // std::ifstream
auto main() -> int {
// Just to demonstrate.
// You want to use your real path instead of example.cpp
auto file = std::ifstream("example.cpp");
auto line = std::string();
while ( std::getline(file, line) )
std::cout << line << '\n';
std::endl(std::cout);
}
Live example

How to display a file in c++?

I need someone to edit that code so that i could display a file!!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string data; //enter a data as a string
ifstream datafile; // input datafile as ifstream
datafile.open("test.txt"); // open test file
}
Unfortunately you didn't specify how you want to read and display the file. Thus I made the assumption that output should go to std::cout. In the attached proposal there are two possibilities to read: line-by-line as you would read the file in any text editor or each word separately in a new line (input separated by White spaces, i.e. blanks, Tabulators or line breaks).
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string data; //enter a data as a string
std::ifstream datafile; // input datafile as ifstream
datafile.open("Source.cpp"); // open test file
// read line by line
while (std::getline(datafile, data))
{
std::cout << data << std::endl;
}
/*
// read each word (separated by white spaces)
while (!datafile.eof())
{
datafile >> data;
std::cout << data << std::endl;
}
*/
datafile.close();
return 0;
}
There is no error handling in. If the file does not exist or any other occurs no exceptions will be caught.

how to convert flowing code into the code which maintains all data how many times i entered [duplicate]

This question already has an answer here:
std::ofstream with std::ate not opening at end
(1 answer)
Closed 4 years ago.
I have a problem with appending a text to a file. I open an ofstream in append mode, still instead of three lines it contains only the last:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream file("sample.txt");
file << "Hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "Again hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "And once again - hello, world!" << endl;
file.close();
string str;
ifstream ifile("sample.txt");
while (getline(ifile, str))
cout << str;
}
// output: And once again - hello, world!
So what's the correct ofstream constructor for appending to a file?
I use a very handy function (similar to PHP file_put_contents)
// Usage example: filePutContents("./yourfile.txt", "content", true);
void filePutContents(const std::string& name, const std::string& content, bool append = false) {
std::ofstream outfile;
if (append)
outfile.open(name, std::ios_base::app);
else
outfile.open(name);
outfile << content;
}
When you need to append something just do:
filePutContents("./yourfile.txt","content",true);
Using this function you don't need to take care of opening/closing. Altho it should not be used in big loops
Use ios_base::app instead of ios_base::ate as ios_base::openmode for ofstream's constructor.

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)