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(arg v[++i]);
if (infile.fail()) {
std::cerr << "Could not open file for reading!\n";
exit(EXIT_FAILU RE);
}
}
}
else if ((option == "-o") || (option == "--outfile")) {
if (argc i)
outfile.open(ar gv[++i]);
if (outfile.fail() ) {
std::cerr << "Could not open file for writing!\n";
exit(EXIT_FAILU RE);
}
}
}
std::vector<str inglines;
if (infile.is_open ()) {
while(getline(i nfile, line)) {
lines.push_back (line);
}
infile.close();
}
else {
while(getline(s td::cin, line)) {
lines.push_back (line);
}
}
std::vector<str ing>::iterator lines_iter;
const std::vector<str ing>::iterator lines_end=lines .end();
if (outfile.is_ope n()) {
for(lines_iter= lines.begin(); lines_iter!=lin es_end; +
+lines_iter)
outfile << *lines_iter << endl;
outfile.close() ;
}
else {
for(lines_iter= lines.begin(); lines_iter!=lin es_end; +
+lines_iter)
cout << *lines_iter << endl;
}
return EXIT_SUCCESS;
} 5 4621
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)
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(st d::istream &infile, std::ostream &outfile)
I can call it like this:
process_file(if stream_filehand le, ofstream_fileha ndle);
or
process_file(if stream_filehand le, std::cout);
or
process_file(st d::cin, std::cout)
Just what I was looking for. Thanks again.
Cliff
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)
"Cliff Martin" <cl**********@g mail.comwrote in message
news:11******** **************@ l53g2000cwa.goo glegroups.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("myf ile.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);
}
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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. read the amount of data I want
4. close the filehandle
|
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 message to the file pointed to by $fh with the time prepended
# and the place appended
sub log_ {
|
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();
|
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 ;
|
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;
| |
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 the FileHandle function. The message is
something like: Shell32.dll missing entry OpenAS_RunDLL!.
On another machine, also running WinXP the problem doesn't occur.
This is the code I use:
|
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 = v.size();
while (true)
|
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 make for much more readable code that is faster to write in
some situations. I've not seen this feature documented anywhere
|
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 at first position.
Thanx in advance !!
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |