Can ofstream be used to write on a printer?
eg:
string nameOfPrinter = "xyz";
ofstream onPrinter(nameOfPrinter);
onPrinter << "Printing.... ";
If I do as above will I get the output by the printer (on the paper) ?
If not, why I won't get the output? Please suggest a way to print using a printer.
I am targeting the Windows platform (32bit)
If you happen to have your printer associated with LPT1 and a printer which support formfeeds.
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream printer ("LPT1");
if(!printer)
{ return 1;
}
printer.puts("Test Test Test\n");
printer.putc('\f');
printer.close();
return 0;
}
LPT1 is also a file name in windows. But as known it is a reserved filename. So it will not be possible to have more than one file with the name LPT1. And this file is already managed by windows.
See for reserved filenames
Yes you can, Your code should be:
ofstream printer;
printer.open("lpt1");
I believe it's case sensitive(not sure "lpt1" or "LPT1"). Also, you'll need to write a page eject command.
EDIT:
LPT (Line Print Terminal) is name of the parallel port interface on IBM PC-compatible computers. Over the years, the parallel port interface has decreased use because of the rise of Universal Serial Bus.
In DOS, the parallel ports could be accessed directly on the command line. For example, the command type c:\autoexec.bat > LPT1 would direct the contents of the autoexec.bat file to the printer port(recognized by the reserved word LPT1"). A PRN device was also available as an alias for LPT1.
Microsoft Windows still refers to the ports in this manner in many cases, though this is often fairly hidden.
In the Linux operating system the first LPT port is available via the filesystem as /dev/lp0.
To write to a printer, one should simply open the printer as if it were a file (the printer name is system-dependent; on Windows machines, it will be lpt1 or prn, while on unix machines, it will be something like /dev/lp), then write whatever text has to be written.
Sample program could be as simple as:
std::ofstream print;
print.open("LPT1");
if (!print)
return 0;
print << data;
print.close();
How would the file stream know the difference between the name of a printer and a file that just happened to share the name of a printer? So no; you can't print to a printer by specifying the name of a printer.
Printing in Win32 is not a trivial task. You can't simply shove some characters at a printer; it needs to know about page layout, fonts, etc. Basically, the way to do it from Win32 is to "draw" to the printer with GDI commands. Beginner-level info can be found here.
Correction: apparently, you can stream output to the printer with a stream. However, it requires that the user has enabled some legacy functionality, so it isn't necessarily always available.
Related
QSerialPortInfo::serialNumber() always returns an empty string, which happens when it's unavailable.
I tried connecting different ports, everything seems allright, but it doesn't show a Serial Number of a port no matter what I do!
Port name, manufacturer, product ID, however, can be correctly outputted.
I didn't connect any devices to the ports, however.
Why can serial number be unavailable? Can this be fixed somehow?
I guess the mistake is somewhere outside code, but here is a slot that I use to access serialNumber() in :
void PortBrowser::onPortChange()
{
int i;
if(comsCombo->currentIndex()>-1)
i =comsCombo->currentIndex();
else
i = 0;
QSerialPort currPort(comsList[i]);
bool opened = currPort.open(QIODevice::ReadOnly);
const QString seriNum = comsList[i].serialNumber();
serNum->setText(seriNum);
manufact->setText(comsList[i].manufacturer());
QTextStream out(stdout);
out<<comsList[i].serialNumber();
currPort.close();
}
If you take a look at the relevant source code parseDeviceSerialNumber() you will see quite some fancy logic where Qt tries to isolate a serial number from some device-identification string. That's the string you are likely also seeing in the Windows device manager way down in the details.
Why can serial number be unavailable? Can this be fixed somehow?
You seem to have a serial port that does not provide its identifier in a format Qt would understand. You could try to come up with a patch for Qt to make it recognize your serial port or you might go and buy a serial port that Qt does recognize. One chipset that is explicitly mentioned in the source code is FTDI.
i implemented program of network statistics with help of powershell scrpit. the program is running successfully and giving me perfact output as well . below is my program.
int main(int argc, char *argv[])
{
string strPath = "C:\\Get-NetworkStatistics.ps1";
char str[50] = "C:\\Get-NetworkStatistics.ps1";
char command[500];
//access function:
//The function returns 0 if the file has the given mode.
//The function returns –1 if the named file does not exist or does not have the given mode
if(access(strPath.c_str(),0) == 0)
{
_snprintf(command, sizeof(command), "Start Powershell.exe -noexit Set -executionpolicy;.'%s';Get-NetworkStatistics",str);
system(command);
}
else
{
system("cls");
cout << "File is not exist";
system("pause");
}
return 0;
}
! here is the output of above program
as you can see the output is in the powershell windows.. i want to fetch all this data of powershell output and want to display it in console. how should it possible?
please help me..
Unless you need to do display the info in realtime as it becomes available, just redirect it to a file, then read that file from C++.
Since netstat was lobotomized in Windows XP SP 2 or thereabouts I can understand using Powershell.
But it may just be that netstat will serve your needs, and then you don't have to deal with any of that complication.
By the way, I recommend using a scripting language for scripting tasks. There is of course the complication that Powershell scripting is disabled by default, otherwise using the Powershell scripting facility would be indicated. But e.g. in this case a [cmd.exe] batch file would be more natural than doing its job from C++.
The Windows Script Host shell objects, available from JScript and VBScript, provide functionality for process execution with output grabbing.
There is a little snag in that you then have to poll the output, but I think it's still easier than doing this at the C/C++ API level.
I'm having problems using native C++ to open a file located on a network drive on a Windows box. My code works fine if the file is local, but fails if the file is on a network share. I can read the file from Windows explorer perfectly fine.
ifstream ifs(cFilename);
if(ifs.is_open())
{
// Read file here. (This never works for a network path)
}
I've also tried this:
struct stat sb;
if (stat(cFilename, &sb) == 0)
{
// Read file here. (This never works for a network path)
}
My path is formatted correctly (e.g. "\\server\filename.ext"), but I still can't open it. Any ideas?
If the name is in the form \\server\filename, then it seems that might not be correct. I believe that typically it needs a share name as well:
\\server\share\filename
Also, make sure that in the code, you escape the backslashes (e.g., \\\\server\\share\\filename).
I wish to print some text directly to a network printer from my c++ code (I am coding with xcode 4). I do know that everything on unix is a file and believe that it would not be impossible to redirect the text using fstream method in c++ to the printer device file. The only problem is I don't know the device file in /dev associated with my network printer.
Is it possible to achieve printing using fstream method? Something like
std::fstream printFile;
printFile.open("//PATH/TO/PRINTER/DEV", std::ios::out);
printFile << "This must go to printer" << std::endl;
printFile.close();
And, if so
How to obtain the file in /dev corresponding to a particular printer?
Thanks in advance,
Nikhil
Opening and writing directly to a file used to be possible back in the days of serial printers; however, this is not the approach available today.
The CUPS daemon provides print queuing, scheduling, and administrative interfaces on OS X and many other Unix systems. You can use the lp(1) or lpr(1) commands to print files. (The different commands come from different versions of print spoolers available in Unix systems over the years; one was derived from the BSD-sources and the other derived from the AT&T sources. For compatibility, CUPS provides both programs.)
You can probably achieve something like you were after with popen(3). In shell, it'd be something like:
echo hello | lp -
The - says to print from standard input.
I haven't tested this, but the popen(3) equivalent would probably look like this:
FILE *f = popen("lp -", "w");
if (!f)
exit(1);
fprintf(f, "output to the printer");
I recommend testing some inputs at the shell first to make sure that CUPS is prepared to handle the formatting of the content you intend to send. You might need to terminate lines with CRLF rather than just \n, otherwise the printer may "stair-step" the output. Or, if you're sending PDF or PS or PCL data, it'd be worthwhile testing that in the cheapest possible manner to make sure the print system works as you expect.
I want to pass a value of an input variable in my program lets say#1 to another program #2 and i want #2 to print the data it got to screen, both are needed to be written in c++. The this will be on Linux.
Depending on the platform there are a number of options available. What you are trying to do is typically called inter-process communication (IPC).
Some options include:
Sockets
Pipes
Queues
Shared Memory
What is easiest is probably dependent on the platform youa are using.
As always, there is a Boost library for that (God, I like Boost).
Nic has covered all the 4 that I wanted to mention (on the same machine):
Sockets
Pipes
Queues
Shared Memory
If writing system calls is troublesome for you, you may want to use the following libraries:
Boost http://www.boost.org/
Poco http://pocoproject.org/blog/
Nokia Qt http://qt.nokia.com/
Something you can read from Qt portable IPC: only QSharedMemory?
If effeciency is not prime concern then use normal file i/o.
else go for IPC to do so.
As far as Windows is concern you have following options :
Clipboard ,
COM ,
Data Copy ,
DDE ,
File Mapping ,
Mailslots ,
Pipes ,
RPC ,
Windows Sockets
For Linux , use can use Name Pipes(efficient) or sockets.
If you're on Windows, you can use Microsoft Message Queueing. This is an example of queue mentioned previously.
If the data to be passed is just a variable, then one of the option is to set it as Environment Variable [ Var1 ] by program #1 and access it, in Program #2 [ if both are running on same env/machine ]. Guess this will be the easiest one, instead of making it complex, by using IPC/socket etc.
I think most of the answers have address the common IPC mechanisms. I'd just like to add that I would probably go for sockets because it's fairly most standard across several platforms. I decided to go for that when I needed to implement IPC that worked both on Symbian Series 60 and Windows Mobile.
The paradigm is straightforward and apart from a few platform glitches, the model worked the same for both platforms. I would also suggest using Protocol Buffers to format the data you send through. Google uses this a lot in its infrastructure. http://code.google.com/p/protobuf/
DBUS
QtDbus
DBus-mm
In response to your comment to Roopesh Majeti's answer, here's a very simple example using environment variables:
First program:
// p1.cpp - set the variable
#include <cstdlib>
using namespace std;;
int main() {
_putenv( "MYVAR=foobar" );
system( "p2.exe" );
}
Second program:
// p2.cpp - read the variable
#include <cstdlib>
#include <iostream>
using namespace std;;
int main() {
char * p = getenv( "MYVAR" );
if ( p == 0 ) {
cout << "Not set" << endl;
}
else {
cout << "Value: " << p << endl;
}
}
Note:
there is no standard way of setting an environment variable
you will need to construct the name=value string from the variable contents
For a very dirt and completely nonprofessional solution you can do it like me.
Save the variable in to a file and then read it (in an infinite loop every x time) with the other program.
fsexample.open("F:/etc etc ...");
fsexample >> data1 >> data2; // etc etc
and on the other side
fsexample.open("F:/etc etc ...");
fsexample << data1 << data2; // etc etc
The trick is that F is a virtual drive created with ramdisk so it is fast
and heavy-duty proof.
You could have problem of simultaneous access but you can check it with
if (!fsexample.is_open()) {
fsexample_error = 1;
}
and retry on failure.