Официальный сайт студ.городка НГТУ
Программирование и БД » stdin и stdout в С 

#1  07.02.10 01:12

Alx
Профиль

stdin и stdout в С

Подскажите как правильно сделать так, чтобы stdin и stdout работали с массивами в памяти.
!!Нужно и читать из stdout и записывать в stdin!!
Есть пока вот такой работающий код:

Код::

#include <stdio.h>
char x[512];
char y[512];
char s[10];
char c ;

int main()
{ 
  setvbuf(stdin,y,_IOFBF,512);
  setvbuf(stdout,x,_IOFBF,512);
  printf("Test\n");

  ungetc('Т',stdin);
  c = getchar();  
  putchar(c);
}

При выполнении printf все нормально, т.е. с stdout сработало:
в массиве x появляется слово и символ Т.
А вот как запихать байты в массив y связанный с stdin пока не могу разобраться.
ungetc - байты зсписывает вовсе не в основной буфер, а в ридбек.

Offline

#2  07.02.10 18:36

$up
Профиль

Re: stdin и stdout в С

вообще, можно попробовать через fprintf(stdin, "test")

Исправлено $up (07.02.10 18:48)

Offline

#3  07.02.10 19:27

Alx
Профиль

Re: stdin и stdout в С

вообще, можно попробовать через fprintf(stdin, "test")

- не помогает (:
stdin только для чтения, вот как туда записать?
пробовал так же с freopen - тоже не вышло

Offline

#4  07.02.10 20:23

$up
Профиль

Re: stdin и stdout в С

я бы предложил с помощью freopen назначить stdin на какой нибудь файл а потом открыть этот файл на запись и писать туда.

Offline

#5  07.02.10 20:55

Alx
Профиль

Re: stdin и stdout в С

пробовал так же с freopen - тоже не вышло

Offline

#6  07.02.10 22:41

$up
Профиль

Re: stdin и stdout в С

Alx, код с freopen покажи

Offline

#7  08.02.10 01:07

Re: stdin и stdout в С

зачем это нужно?

Offline

#8  08.02.10 07:02

Alx
Профиль

Re: stdin и stdout в С

зачем это нужно?

Я вообще хочу работать с UARTом,
используя функции printf и scanf из стандартной библиотеки.
По прерыванию "UART TX EMPTY" вытаскиваю все из буфера и посылаю в порт.
По "UART RX NOT EMPTY" записываю в буфер.
Вот мне и надо связать stdin и stdout c этими буферами.

Исправлено Alx (08.02.10 07:06)

Offline

#9  08.02.10 11:38

$up
Профиль

Re: stdin и stdout в С

Alx, ты под что пишешь то?
Обычно открывается com порт как файл mystdout и потом просто подменяется stdout = &mystdout

Offline

#10  08.02.10 14:12

Re: stdin и stdout в С

Alx написал(а):

stdin только для чтения, вот как туда записать?

stdin - стандартный поток ввода... из потока ввода можно только читать, но никак не писать...

Offline

#11  08.02.10 18:28

Alx
Профиль

Re: stdin и stdout в С

подменяется stdout = &mystdout

с stdout то у меня работает.
А про stdin пишет, что "must be a modifiable value" так что не пройдет.

из потока ввода можно только читать, но никак не писать

а как клавиатура туда попадает?

Offline

#12  08.02.10 19:02

$up
Профиль

Re: stdin и stdout в С

Alx, так ты бы написал, каким компилятором пользуешься.

Offline

#13  08.02.10 20:08

Alx
Профиль

Re: stdin и stdout в С

IAR EW 4.20.1. А есть разница?  Библиотека же "стандартная".

Offline

#14  08.02.10 23:26

$up
Профиль

Re: stdin и stdout в С

Alx, конечно, разница имеется.
в IAR достаточно переопределить
size_t __write(int Handle, const unsigned char * buf, size_t bufcount);
size_t __read(int Handle, unsigned char * buffer, size_t bufcount);
и все функции stdio будут их использовать

выдержка из хелпа
Standard streams for input and output
There are three standard communication channels (streams)—stdin, stdout, and
stderr—which are defined in stdio.h. If any of these streams are used by your
application, for example by the functions printf and scanf, you need to customize the
low-level functionality to suit your hardware.
There are primitive I/O functions, which are the fundamental functions through which
C and C++ performs all character-based I/O. For any character-based I/O to be available,
you must provide definitions for these functions using whatever facilities the hardware
environment provides.
IMPLEMENTING LOW-LEVEL CHARACTER INPUT AND
OUTPUT
To implement low-level functionality of the stdin and stdout streams, you must write
the functions __read and __write, respectively. You can find template source code for
these functions in the 430\src\lib directory.
If you intend to rebuild the library, the source files are available in the template library
project, see Building and using a customized library, page 55. Note that customizing the
low-level routines for input and output does not require you to rebuild the library.
Note: If you write your own variants of __read or __write, special considerations
for the C-SPY runtime interface are needed, see C-SPY Debugger runtime interface,
page 69.

Код::

/*******************
 *
 * Copyright 1998-2003 IAR Systems.  All rights reserved.
 *
 * $Revision: 38614 $
 *
 * This is a template implementation of the "__write" function used by
 * the standard library.  Replace it with a system-specific
 * implementation.
 *
 * The "__write" function should output "size" number of bytes from
 * "buffer" in some application-specific way.  It should return the
 * number of characters written, or _LLIO_ERROR on failure.
 *
 * If "buffer" is zero then __write should perform flushing of
 * internal buffers, if any.  In this case "handle" can be -1 to
 * indicate that all handles should be flushed.
 *
 * The template implementation below assumes that the application
 * provides the function "MyLowLevelPutchar".  It should return the
 * character written, or -1 on failure.
 *
 ********************/

#include <yfuns.h>

_STD_BEGIN

#pragma module_name = "?__write"

int MyLowLevelPutchar(int x);

/*
 * If the __write implementation uses internal buffering, uncomment
 * the following line to ensure that we are called with "buffer" as 0
 * (i.e. flush) when the application terminates.
 */

size_t __write(int handle, const unsigned char * buffer, size_t size)
{
  /* Remove the #if #endif pair to enable the implementation */
#if 0    

  size_t nChars = 0;

  if (buffer == 0)
  {
    /*
     * This means that we should flush internal buffers.  Since we
     * don't we just return.  (Remember, "handle" == -1 means that all
     * handles should be flushed.)
     */
    return 0;
  }

  /* This template only writes to "standard out" and "standard err",
   * for all other file handles it returns failure. */
  if (handle != _LLIO_STDOUT && handle != _LLIO_STDERR)
  {
    return _LLIO_ERROR;
  }

  for (/* Empty */; size != 0; --size)
  {
    if (MyLowLevelPutchar(*buffer++) < 0)
    {
      return _LLIO_ERROR;
    }

    ++nChars;
  }

  return nChars;

#else

  /* Always return error code when implementation is disabled. */
  return _LLIO_ERROR;

#endif

}

_STD_END

Код::

/*******************
 *
 * Copyright 1998-2003 IAR Systems.  All rights reserved.
 *
 * $Revision: 38614 $
 *
 * This is a template implementation of the "__read" function used by
 * the standard library.  Replace it with a system-specific
 * implementation.
 *
 * The "__read" function reads a number of bytes, at most "size" into
 * the memory area pointed to by "buffer".  It returns the number of
 * bytes read, 0 at the end of the file, or _LLIO_ERROR if failure
 * occurs.
 *
 * The template implementation below assumes that the application
 * provides the function "MyLowLevelGetchar".  It should return a
 * character value, or -1 on failure.
 *
 ********************/

#include <yfuns.h>

_STD_BEGIN

#pragma module_name = "?__read"

int MyLowLevelGetchar();

size_t __read(int handle, unsigned char * buffer, size_t size)
{
  /* Remove the #if #endif pair to enable the implementation */
#if 0    

  int nChars = 0;

  /* This template only reads from "standard in", for all other file
   * handles it returns failure. */
  if (handle != _LLIO_STDIN)
  {
    return _LLIO_ERROR;
  }

  for (/* Empty */; size > 0; --size)
  {
    int c = MyLowLevelGetchar();
    if (c < 0)
      break;

    *buffer++ = c;
    ++nChars;
  }

  return nChars;

#else

  /* Always return error code when implementation is disabled. */
  return _LLIO_ERROR;

#endif
}

_STD_END

Offline

#15  09.02.10 06:05

Alx
Профиль

Re: stdin и stdout в С

да, спасибо уже сделал.
Правда хотелось бы более простой метод и не зависимый от платформы.

Исправлено Alx (09.02.10 06:08)

Offline

Программирование и БД » stdin и stdout в С 

ФутЕр:)

© Hostel Web Group, 2002-2025.   Сообщить об ошибке

Сгенерировано за 0.220 сек.
Выполнено 11 запросов.