Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ofstream be used for printing on a printer

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)

like image 467
Suhail Gupta Avatar asked Jul 01 '11 08:07

Suhail Gupta


2 Answers

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

like image 151
fyr Avatar answered Nov 09 '22 23:11

fyr


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();
like image 30
Alok Save Avatar answered Nov 09 '22 23:11

Alok Save