I have a piece of code (see below) that reads data from a file given as a command line argument. I would like to add a support for being able to read the input from a pipe. For instance, the current version reads the data as main <file_name>
, whereas it should also be possible to do something line cmd1 | main
. Here is the source to read data from file:
procedure main is
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count /= 1 then
return;
else
Ada.Text_IO.Open (
File => File,
Mode => In_File,
Name => Ada.Command_Line.Argument (1));
while (not Ada.Text_IO.End_Of_File (File)) loop
-- Read line using Ada.Text_IO.Get_Line
-- Process the line
end loop;
Ada.Text_IO.Close (File);
end main;
If I understood correctly, a pipe is just a non-regular file type in Ada. But how do I deal with it?
None of these seem to really answer your question. A pipe merely makes the standard output of another program be the standard input of your program, so you read a pipe by reading Standard_Input.
The function Current_Input returns a File_Type. It initially returns Standard_Input, but calling Set_Input changes it to return whatever you passed to Set_Input. So a rough outline of how to read from Standard_Input if no file is given, and from the given file if one is, looks like:
You don't even need to create a file to be able to read data from pipe.
just
And after that
type ..\src\main.adb | main.exe
works.Quoting from the ARM...
which allow you to manipulate the default pipes
stdin, stdout, stderr
as files; either as pre-opened files (input and output pipes) or allow you to redirect stdout to your own file, etc.This example shows redirecting one of the standard pipes to a file and restoring it to the system provided file. Alternatively, File I/O subprograms may be called with the File argument set to e.g.
Ada.Text_IO.Standard_Output
and should simply work as expected - outputting to Terminal or to whatever you pipedstdout
to on the commandline.Similar facilities should be available in
Direct_IO, Sequential_IO, Stream_IO
etc if the data you're reading and writing isn't text.Timur's answer shows you can read and write directly to these pipes; this answer's approach allows you to treat the standard pipes uniformly with other files, so that you can I/O either via file or pipe with the same code. For example, if a commandline filename is supplied, use that file, otherwise point your File at
Standard_Output
.And if you're asking what happens in the command line
cmd1|main|grep "hello"
, yes, the output of cmd1 is on a pipe calledstdout
(in C) orStandard_Output
(Ada) which is connected via the (Unix-specific pipe command) | to theStandard_Input
of yourmain
program written in Ada. In turn, itsStandard_Output
is piped into grep'sstdin
which it searches for "hello".If you are asking how you open and access named pipes, I suspect that is OS specific, and may be a more difficult question.
(In which case, this Stack Exchange Q&A may help).