Windows console output to file and console

Методы ввода и вывода Input and Output Methods

Существует два разных подхода к вводу-выводу в консоль, выбор которых зависит от того, насколько гибка и контролируется потребность в приложении. There are two different approaches to console I/O, the choice of which depends on how much flexibility and control an application needs. Высокоуровневый подход обеспечивает простой потоковый ввод-вывод, но ограничивает доступ к входным и экранным буферам консоли. The high-level approach enables simple character stream I/O, but it limits access to a console’s input and screen buffers. Для низкоуровневого подхода требуется, чтобы разработчики записывали больше кода и выбрали более широкий спектр функций, но это также предоставляет приложению большую гибкость. The low-level approach requires that developers write more code and choose among a greater range of functions, but it also gives an application more flexibility.

Подход низкого уровня не рекомендуется для новой и текущей разработки. The low-level approach is not recommended for new and ongoing development. Приложениям, которым требуются функциональные возможности низкоуровневых функций консольного ввода-вывода, рекомендуется использовать Виртуальные последовательности и исследовать документацию по классическим функциям и виртуальному терминалу , а также к стратегии экосистемы. Applications needing functionality from the low-level console I/O functions are encouraged to use virtual terminal sequences and explore our documentation on both classic functions versus virtual terminal and the ecosystem roadmap.

Приложение может использовать функции файлового ввода-вывода, ReadFile и WriteFile, а также консольные функции реадконсоле и вритеконсоледля высокого уровня ввода-вывода, обеспечивающего косвенный доступ к входным и буферам экрана консоли. An application can use the file I/O functions, ReadFile and WriteFile, and the console functions, ReadConsole and WriteConsole, for high-level I/O that provides indirect access to a console’s input and screen buffers. Входные функции высокого уровня фильтруют и обрабатывают данные в входном буфере консоли для возврата входных данных в виде потока символов, отменяя Ввод размера буфера и мыши. The high-level input functions filter and process the data in a console’s input buffer to return input as a stream of characters, discarding mouse and buffer-resizing input. Аналогичным образом, выходные функции верхнего уровня записывают поток символов, отображаемый в текущем положении курсора в буфере экрана. Similarly, the high-level output functions write a stream of characters that are displayed at the current cursor location in a screen buffer. Приложение управляет способом работы этих функций, устанавливая режимы ввода-вывода консоли. An application controls the way these functions work by setting a console’s I/O modes.

Низкоуровневые функции ввода-вывода предоставляют прямой доступ к входным и экранным буферам консоли, позволяя приложению обращаться к событиям ввода и изменения размера буфера мыши, а также расширенной информации для событий клавиатуры. The low-level I/O functions provide direct access to a console’s input and screen buffers, enabling an application to access mouse and buffer-resizing input events and extended information for keyboard events. Низкоуровневые функции вывода позволяют приложению считывать или записывать данные в указанное число последовательных символьных ячеек в буфере экрана, а также читать или записывать в прямоугольные блоки символьных ячеек в указанном месте в буфере экрана. Low-level output functions enable an application to read from or write to a specified number of consecutive character cells in a screen buffer, or to read or write to rectangular blocks of character cells at a specified location in a screen buffer. Входные режимы консоли влияют на вход низкого уровня, позволяя приложению определить, помещаются ли в входной буфер события, связанные с мышью и изменением размера буфера. A console’s input modes affect low-level input by enabling the application to determine whether mouse and buffer-resizing events are placed in the input buffer. Режимы вывода консоли не влияют на выходные данные низкого уровня. A console’s output modes have no effect on low-level output.

Читайте также:  Драйвера для рутокена линукс

Методы ввода-вывода высокого и нижнего уровней не являются взаимоисключающими, и приложение может использовать любое сочетание этих функций. The high-level and low-level I/O methods are not mutually exclusive, and an application can use any combination of these functions. Однако, как правило, приложение использует один и тот же подход, и мы рекомендуем сосредоточиться на одной конкретной парадигме для достижения оптимальных результатов. Typically, however, an application uses one approach or the other exclusively and we recommend focusing on one particular paradigm for optimal results.

Идеальное приложение для прямого просмотра будет сосредоточиться на высокоуровневых методах и дополнять дополнительные потребности с помощью виртуальных последовательностей с помощью методов ввода-вывода высокого уровня, когда это необходимо, избегая использования функций низкоуровневого ввода-вывода полностью. The ideal forward looking application will focus on the high-level methods and augment further needs with virtual terminal sequences through the high-level I/O methods when necessary avoiding the use of low-level I/O functions entirely.

В следующих разделах описываются режимы консоли и функции ввода-вывода высокого уровня и низкого уровня. The following topics describe the console modes and the high-level and low-level I/O functions.

How can I redirect console output to file?

I’m new to c. Is there any simple way to redirect all the console’s output (printfs etc.) to a file using some general command line \ linkage parameter (without having to modify any of the original code)?

If so what is the procedure?

4 Answers 4

Use shell output redirection

The standard error will still be output to the console. If you don’t want that, use:

your-command > outputfile.txt 2>&1

You should also look into the tee utility, which can make it redirect to two places at once.

On unices, you can also do:

That way you’ll see the output and be able to interact with the program, while getting a hardcopy of the standard output (but not standard input, so it’s not like a teletype session).

As mentioned above, you can use the > operator to redirect the output of your program to a file as in:

Also, you can append data to an existing file (or create it if it doesnt exit already by using >> operator:

If you really want to learn more about the (awesome) features that the command line has to offer I would really recommend reading this book (and doing lots of programming :))

In Unix shells you can usually do executable > file 2> &1 , whch means «redirect standard output to file and error output to standard output»

Not the answer you’re looking for? Browse other questions tagged c shell io-redirection or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Windows console output to file and console

This forum is closed. Thank you for your contributions.

Answered by:

Question

in my .bat file i have added the following to a command : >> c:\1.txt

This will log the output to 1.txt, but not to my console/screen anymore.

What is the command to have the output to the console AND 1.txt?

Answers

You are looking to output to the console and standard output simultaneously, more commonly known as «tee».

In PowerShell you can use the Tee-Object command. There is not an equivalent in cmd.exe unless you use an external tee program, such as tee.exe. If you have tee.exe, you can write:

(-a means append rather than overwrite file)

There isn’t one that is intrinsic to cmd.exe. If you want you can either search for a unix TEE utility port to Windows or use the following hybrid VBS/batch procedure to do that .

So there is no option in CMD to have output to both??

No. Cmd.exe does not have any way to tee output natively.

Читайте также:  Mac os терминал узнать размер папки

All replies

You are looking to output to the console and standard output simultaneously, more commonly known as «tee».

In PowerShell you can use the Tee-Object command. There is not an equivalent in cmd.exe unless you use an external tee program, such as tee.exe. If you have tee.exe, you can write:

(-a means append rather than overwrite file)

There isn’t one that is intrinsic to cmd.exe. If you want you can either search for a unix TEE utility port to Windows or use the following hybrid VBS/batch procedure to do that .

Just because you don’t like the answer doesn’t mean that it isn’t so. Two of us have provided pretty much identical answers. Are you looking for a third opinion ;^)) Sorry to disappoint, but I seriously doubt you’re going to get one.

So there is no option in CMD to have output to both??

No. Cmd.exe does not have any way to tee output natively.

echo command >> log1.txt 2>>&1 1>>CON 2>>CON

echo command >> log1.txt 1>>CON

CON will print in console, 1 is first output

Bhavani this helped a ton and solved my problem thank you!!

a. one batch file instead of batch to call batch

b. wrap code in parens

) > test.txt && type test.txt

-this logs to console first, at the very end it generates the log file once completed

blend with idea from here to use «type»

Bhavani this helped a ton and solved my problem thank you!!

a. one batch file instead of batch to call batch

b. wrap code in parens

) > test.txt && type test.txt

-this logs to console first, at the very end it generates the log file once completed

blend with idea from here to use «type»

It will log entire command output to text file.And then it is displaying the content of the text file.

any command like compilation of a project.

devenv /Build «Release|x64» «w:/Frameworks/Frameworks.sln»

THis command will take almost 1 hour to complete.

How to output console or PowerShell transcript to a file in Windows

This post was most recently updated on December 7th, 2020.

Every now and then, you run into a situation, where you’ll need to somehow dump the console output (or transcript) of running a console application. I’m actually going to argue it happens a lot more often than one would think – in my case, any time a customer requires a webjob or a function, that one would normally deploy to Azure, being ran on the servers of the customer. This post describes how to do that.

Problem

Table of Contents

Something breaks or the app crashes, and the error is logged to event log… But just the error, not the whole transcript. You’d like to get it all, to figure out what’s actually going on, but event log is not the way to go.

Or, maybe you’re investigating an error that happened to someone else, but only get screenshots of console or event log errors, whereas you’d want to get all the possible information about the problem instead.

Solution: redirection operator > to the rescue!

It’s luckily pretty easy. There are multiple ways to pipe, dump, redirect, log, mirror or just save the output to almost any imaginable target medium, but since I hate always googling for them (and for the life of me, I can’t seem to remember it by heart), I’m documenting my preferred way here.

No need to pipe output to file – because the redirection does natively what you could do with a pipe and “Out-File -FilePath” or similar command.

How to redirect output to file in Powershell?

You can direct the whole console output (and hence the whole PowerShell transcript for your executable) to a text file by doing something like this:

executable.exe > output.txt 2>&1

executable.exe *>&1 > output.txt

This method just writes everything from the console window to a file – as simple as that!

And of course, it’s not only limited to Command Prompt (cmd.exe) – it also works in Windows PowerShell:

If you want to verify this works, you can run the following in PowerShell – it first outputs “Hello World” and then simply redirects it to the file output.txt:

Читайте также:  Курсор мыши для linux

echo “Hello World” >output.txt 2>&1 .\output.txt

The second command should open output.txt in text editor – and it should contain “Hello World”.

In these examples, the following parameters affect the outcome:

Element Description
Redirection operator: > Writes the command output to a file or a device, such as a printer, instead of the Command Prompt window.
2>&1 These parameters cause this command to first redirect stdout (Standard Output Stream) to the output file, and then redirects stderr (Standard Error Stream) there as well.

For a more thorough list of different operators available, see here.

Okay – so now it’s finally documented. Maybe I won’t have to google it the next time 🙂

Wait… But how is this better than copypasting from a console window?

If you’re not running your application unattended, you could just run the application and copy-paste from the window to your preferred location. That’s nice and easy! So what makes this method better?

A couple of things come to mind:

Why dumping console output to a file is better than just copypasting

  1. You can get the transcripts unattended. You don’t have to do anything yourself.
  2. This way, You won’t mess the copying up by selecting from areas of the output.
    • I don’t know about you, but I often mess up the copy-pasting from a console or PowerShell window. This method makes that impossible.
  3. This is the easiest way I’ve found to ask other people for the whole output/transcript of a console application run.
    • That’s really useful, because when I’m debugging, I really want the whole log, and not just the last few lines of red text!

Further thoughts

For more info and options about the output scenarios, see this Stack Overflow thread. If you want to read more about stdout and stderr, check this out.

And for further reference, here’s a list of all supported redirection operators for reasonably recent PowerShell versions (probably valid for PowerShell >5.1):

Redirection What’s it do?
> Sends output to the specified file
>> Appends output to the content of the
specified file
2> Sends errors to the specified file.
2>> Appends errors to the content of the
specified file
2>&1 Sends errors and success output to the
success output stream
3> Sends warnings to the specified file
3>> Appends warnings to the contents of the
specified file.
3>&1 Sends warnings and success output to the
success output stream
4> Sends verbose output to the specified file
4>> Appends verbose output to the contents of
the specified file
4>&1 Sends verbose output and success output to
the success output stream
5> Sends debug messages to the specified file
5>> Appends debug messages to the contents of
the specified file
5>&1 Sends debug messages and success output to
the success output stream
6> Sends informational messages to a specified
file
6>> Appends informational messages to the
contents of a specified file
6>&1 Sends informational messages and success
output to the success output stream.
*> Sends all output types to the specified file
*>> Appends all output types to the contents of
the specified file
*>&1 Sends all output types to the success output
stream

Source (applied)

However, a far more advanced scenario would be to save the output directly to Application Insights or something similar. For a lot of cases, this would be like shooting a fly with a bazooka, but for larger deployments, why not. Maybe worth a blog post later!

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That’s definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet.

He’s been a developer from 2004 (starting with PHP and Java), and he’s been bending and twisting SharePoint into different shapes since MOSS. Nowadays he’s not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff. He’s also Microsoft MVP for Office Development.

Оцените статью