Read from file or stdin

You’re thinking it wrong. What you are trying to do: If stdin exists use it, else check whether the user supplied a filename. What you should be doing instead: If the user supplies a filename, then use the filename. Else use stdin. You cannot know the total length of an incoming stream unless you read … Read more

flush in java.io.FileWriter

Writers and streams usually buffer some of your output data in memory and try to write it in bigger blocks at a time. flushing will cause an immediate write to disk from the buffer, so if the program crashes that data won’t be lost. Of course there’s no guarantee, as the disk may not physically … Read more

Get file name from byte array or Stream

If the Stream is actually a FileStream, then this may be available by casting to FileStream and accessing the .Name property: Stream stream = … FileStream fs = stream as FileStream; if(fs != null) Console.WriteLine(fs.Name); However, in the general case: no, this is not available. A byte[] certainly has no concept of a filename, nor … Read more

Resource leak in Files.list(Path dir) when stream is not explicitly closed?

If you close the Stream, Files.list() does close the underlying DirectoryStream it uses to stream the files, so there should be no resource leak as long as you close the Stream. You can see where the DirectoryStream is closed in the source code for Files.list() here: return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false) .onClose(asUncheckedRunnable(ds)); The key thing to … Read more

How to read the first byte of a subprocess’s stdout and then discard the rest in Python?

If you’re using Python 3.3+, you can use the DEVNULL special value for stdout and stderr to discard subprocess output. from subprocess import Popen, DEVNULL process = Popen([“mycmd”, “myarg”], stdout=DEVNULL, stderr=DEVNULL) Or if you’re using Python 2.4+, you can simulate this with: import os from subprocess import Popen DEVNULL = open(os.devnull, ‘wb’) process = Popen([“mycmd”, … Read more

Creating an input stream from constant memory

The way to do this is to create a suitable stream buffer. This can, e.g., be done like this: #include <streambuf> #include <istream> struct membuf: std::streambuf { membuf(char const* base, size_t size) { char* p(const_cast<char*>(base)); this->setg(p, p, p + size); } }; struct imemstream: virtual membuf, std::istream { imemstream(char const* base, size_t size) : membuf(base, … Read more

tech