How can I close a stream without knowing its name?

If I initialise a stream as follows

OpenWrite["~/example"]


How do I close this stream? Close seems to expect a name, but I do not know the name of the stream in this format.

 - Thanks for all the responses. It seems the simplest solution was

Close[<full path name to file>]


I had previously tried Close["~/example"] but to no avail.

-
Check Streams[] for it. When you use OpenWrite, you'd normally save the return value (the stream object), otherwise you can't use the stream at all. So under normal usage, this would not be a problem. – Szabolcs Nov 22 '13 at 21:53

OpenWrite returns the stream it opens, so do this

str = OpenWrite["~/example"]

OutputStream["/Users/oldmg/example", 83]

Close[str]


Also, all streams have a name. In this case it is "/Users/oldmg/example".

-

In the event you did not save the stream object for some reason, You should be able to close by the file name, ie. simply

 Close["~/example"]

-
Won't work. The stream name has "~" expanded to the full path. – m_goldberg Nov 23 '13 at 2:21
Use Close[FileNameJoin[{\$HomeDirectory, "example"}]] instead. – Michael E2 Nov 23 '13 at 3:34
You can also use Close[ExpandFileName["~/example"]]. – Michael E2 Nov 23 '13 at 17:39

Typical usage:

(Write[#, "file contents"]; Close[#]) &@OpenWrite["test"];
(*
file contents
*)

-

The simplest, most general way to do this is probably via Streams[].

Set up some data ...

test = StringTake[ExampleData[{"Text", "DeclarationOfIndependence"}],
50] (* sample data ... *);
str = StringToStream[#] & /@
StringSplit[test]; (* converted to streams *)


Now the example ...

Streams[] (* all streams *)
ostr = Select[Streams[], SameQ[Head[#], InputStream] &] (* select inputStreamsonly *);
Close[#] & /@ ostr (* now close all the input streams ... *);
Streams[] (* only output streams remain*)

-