473,385 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Assign cout or cin to a filehandle

Hi,

I am writing a simple filter type program that can take input from
file or stdin, and output to a file or stdout. It would make life much
easier if I could assign cin to a ifstream object and read it like a
file and do the same for cout (to an ofstream). Any ideas how I could
do this? Or perhaps some comments on how I could redo the code to do
what I want? Simplified code follows:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

using std::cout;
using std::endl;
using std::string;

void usage(void);

int main(int argc, char* argv[]) {
string fields;

string line;
std::ifstream infile;
std::ofstream outfile;
for (int i=0; i<argc; i++) {
string option = argv[i];
std::transform(option.begin(), option.end(), option.begin(),
tolower);

if ((option == "-i") || (option == "--infile"))
{
if (argc i) {
infile.open(argv[++i]);
if (infile.fail()) {
std::cerr << "Could not open file for reading!\n";
exit(EXIT_FAILURE);
}
}
}
else if ((option == "-o") || (option == "--outfile")) {
if (argc i)
outfile.open(argv[++i]);
if (outfile.fail()) {
std::cerr << "Could not open file for writing!\n";
exit(EXIT_FAILURE);
}
}
}

std::vector<stringlines;
if (infile.is_open()) {
while(getline(infile, line)) {
lines.push_back(line);
}

infile.close();
}
else {
while(getline(std::cin, line)) {
lines.push_back(line);
}
}

std::vector<string>::iterator lines_iter;
const std::vector<string>::iterator lines_end=lines.end();
if (outfile.is_open()) {
for(lines_iter=lines.begin(); lines_iter!=lines_end; +
+lines_iter)
outfile << *lines_iter << endl;

outfile.close();
}
else {
for(lines_iter=lines.begin(); lines_iter!=lines_end; +
+lines_iter)
cout << *lines_iter << endl;
}

return EXIT_SUCCESS;
}

Feb 8 '07 #1
5 4604
Cliff Martin wrote:
>
I am writing a simple filter type program that can take input from
file or stdin, and output to a file or stdout. It would make life much
easier if I could assign cin to a ifstream object and read it like a
file and do the same for cout (to an ofstream). Any ideas how I could
do this?
Nope. But that's not the best approach. The type of the standard input
stream is a class derived from std::istream, and the types of the
standard output streams are derived from std::ostream. Similarly,
std::ifstream is derived from std::istream, and std::ofstream is derived
from std::ostream. So write your I/O functions to take istreams and
ostreams by reference, and call them with the appropriate object.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Feb 8 '07 #2
from std::ostream. So write your I/O functions to take istreams and
ostreams by reference, and call them with the appropriate object.

-- Pete
That worked, thanks. I open the files pass them in to a function as an
istream or ostream reference. If the filename was not provided for
either, I pass in std::cout or std::cin.

so with a function like this:
process_file(std::istream &infile, std::ostream &outfile)

I can call it like this:

process_file(ifstream_filehandle, ofstream_filehandle);

or

process_file(ifstream_filehandle, std::cout);

or

process_file(std::cin, std::cout)

Just what I was looking for. Thanks again.

Cliff

Feb 9 '07 #3
Cliff Martin wrote:
>
Just what I was looking for. Thanks again.
That's the power of object-oriented programming.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Feb 9 '07 #4

"Cliff Martin" <cl**********@gmail.comwrote in message
news:11**********************@l53g2000cwa.googlegr oups.com...
Hi,

I am writing a simple filter type program that can take input from
file or stdin, and output to a file or stdout. It would make life much
easier if I could assign cin to a ifstream object and read it like a
file and do the same for cout (to an ofstream). Any ideas how I could
do this?
Pete already showed you the better approach, but it is possible to "assign"
a stream to another. I used quotation marks because you're not really
assigning them, rather you're replacing the underlaying stream buffers that
are responsible for the actual IO of the streams:

#include <iostream>
#include <fstream>

int main()
{
// create a new streambuf object that writes to a file
std::filebuf outFileBuf("myfile.txt", std::ios::out);

// set the streambuf object to cout and store the previous streambuf
std::streambuf * oldBuf = std::cout.rdbuf(&outFileBuf);

std::cout << "This writes to myfile.txt rather than stdout" <<
std::endl;

// restore original streambuf
std::cout.rdbuf(oldBuf);
}
Feb 9 '07 #5
Cliff Martin wrote:
I am writing a simple filter type program that can take input from
file or stdin, and output to a file or stdout. It would make life much
easier if I could assign cin to a ifstream object and read it like a
file and do the same for cout (to an ofstream). Any ideas how I could
do this? Or perhaps some comments on how I could redo the code to do
what I want? Simplified code follows:
You can use an ofstream and a ifstream. Create each of them without
arguments and, depending on the situation, open the file or use rdbuf to
make the underlying stream use the streambuf of cin or cout.

--
Salu2
Feb 9 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jorge Godoy | last post by:
Hi! I'm trying to get a specific information from inside an image and it works correctly on unices. What I do is: 1. associate a filehandle with the image file 2. get the desired line 3....
1
by: Eduard W. Lohmann | last post by:
Hello. I write this little thing to help me log from several instances of the same class in apache, mod_perl. But I can't figure one thing out. package Logger; require Carp; # Write the...
2
by: Bill | last post by:
I'm trying to use a hash key as a filehandle like so. #!/usr/local/bin/perl use strict; my %buf = ( 'F00' => 'foo.dat' ); &open_files();
18
by: ineedyourluvin1 | last post by:
Hi, I would appreciate if someone could tell me what I'm doing wrong ? #include<iostream> using namepace std ; struct person{ char *firstname ; int age ;
8
by: nrhayyal | last post by:
hi all, is it a good idea to assign object to pointers without initialising it to NULL? suppose if i have a class TEST class ELEMENT { private: int a; string s1;
1
by: Zairay | last post by:
Hi All, I'm having a problem with the Shell32.dll when I try to open a program from my Access db. When I try to open a program called FalconViewLite from my access database I get an error in...
15
by: Lambda | last post by:
I'm writing a function to partition a vector according to a predicate. For example: vector<string>::size_type partition(vector<Student_info&v) { vector<string>::size_type i, j; i = -1; j =...
29
by: stephen b | last post by:
Hi all, personally I'd love to be able to do something like this: vector<intv; v.assign(1, 2, 5, 9, 8, 7) etc without having to manually add elements by doing v = 1, v = 2 .. etc. it would...
7
by: freshpetals | last post by:
Hello people..I just wanted to know that can we store number of files in a filehandle ..if yes how could we do that???I did write a program but its just parsing result from the file which I'm giving...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.