Прочитайте онлайн язык си — руководство для начинающих
Содержание:
- Альтернативы getchar()
- RemarksRemarks
- Remarks
- ТребованияRequirements
- Возвращаемое значениеReturn Value
- RemarksRemarks
- ТребованияRequirements
- ERRORS top
- 傳回值Return Value
- COPYRIGHT top
- КомментарииRemarks
- Решение задач
- DESCRIPTION top
- 返回值Return Value
- Функция языка Си scanf
- Функция языка Си gets
- 返回值Return Value
- DESCRIPTION top
- ТребованияRequirements
- 备注Remarks
- Description
Альтернативы getchar()
Так как getchar(), имеющаяся в библиотеке компилятора, может оказаться неподходящей в интерактивной среде, то для чтения символов с клавиатуры может потребоваться другая функция. В стандарте языка С не определяется никаких функций, которые гарантировали бы интерактивный ввод, но их определения имеются буквально в библиотеках всех компиляторов С. И пусть в стандарте С эти функции не определены, но известны они всем! А известны они благодаря функции getchar(), которая для большинства программистов явно не подходит.
У двух из самых распространенных альтернативных функций getch() и getche() имеются следующие прототипы:
В библиотеках большинства компиляторов прототипы таких функций находятся в заголовочном файле <conio.h>. В библиотеках некоторых компиляторов имена этих функций начинаются со знака подчеркивания (_). Например, в Visual C++ компании Microsoft они называются _getch() и _getche().
Функция getch() ожидает нажатия клавиши, после которого она немедленно возвращает значение. Причем, символ, введенный с клавиатуры, на экране не отображается. Имеется еще и функция getche(), которая хоть и такая же, как getch(), но символ на экране отображает. И если в интерактивной программе необходимо прочитать символ с клавиатуры, то часто вместо getchar() применяется getche() или getch(). Вот, например, предыдущая программа, в которой getchar() заменена функцией getch():
Когда выполняется эта версия программы, при каждом нажатии клавиши соответствующий символ сразу передается программе и выводится на другом регистре. А ввод в строках не буферизируется. И хотя в кодах в этой книге функции getch() и getche() больше не встречаются, но они вполне могут пригодиться в тех программах, которые напишете вы.
На заметку | Тогда: когда писались эти слова, при использовании компилятора Visual C++ компании Microsoft функции _getch() и getch() были несовместимы с функциями ввода стандартного С, например, с функциями scanf() или gets(). Поэтому вам придется вместо стандартных функций использовать такие их специальные версии, как cscanf() или cgets(). Чтобы получить более подробную информацию, следует изучить документацию по Visual C++. |
RemarksRemarks
Функция ungetc помещает символ c обратно в Stream и очищает индикатор конца файла.The ungetc function pushes the character c back onto stream and clears the end-of-file indicator. Поток должен быть открыт для чтения.The stream must be open for reading. Последующая операция чтения в потоке начинается с c.A subsequent read operation on stream starts with c. Попытка принудительной отправки EOF в поток с помощью ungetc игнорируется.An attempt to push EOF onto the stream using ungetc is ignored.
Символы, помещаемые в поток с помощью ungetc , могут быть стерты при вызове fflush, fseek, fsetposили Rewind перед считыванием символа из потока.Characters placed on the stream by ungetc may be erased if fflush, fseek, fsetpos, or rewind is called before the character is read from the stream. Индикатор позиции в файле будет иметь значение, которое было до помещения символов обратно.The file-position indicator will have the value it had before the characters were pushed back. Внешнее хранилище, соответствующее потоку, не изменяется.The external storage corresponding to the stream is unchanged. При успешном вызове ungetc для текстового потока индикатор положения файла не определен до тех пор, пока все символы, отправленные обратно, не будут прочитаны или отменены.On a successful ungetc call against a text stream, the file-position indicator is unspecified until all the pushed-back characters are read or discarded. При каждом успешном вызове ungetc для двоичного потока индикатор положения файла уменьшается; Если его значение было равно 0 перед вызовом, то после вызова значение не определено.On each successful ungetc call against a binary stream, the file-position indicator is decremented; if its value was 0 before a call, the value is undefined after the call.
Результаты непредсказуемы, если ungetc вызывается дважды без операции чтения или размещения файла между двумя вызовами.Results are unpredictable if ungetc is called twice without a read or file-positioning operation between the two calls. После вызова fscanfвызов ungetc может завершиться ошибкой, если не была выполнена другая операция чтения (например, getc).After a call to fscanf, a call to ungetc may fail unless another read operation (such as getc) has been performed. Это обусловлено тем, что fscanf вызывает ungetc.This is because fscanf itself calls ungetc.
ungetwc — это версия ungetcдля расширенных символов.ungetwc is a wide-character version of ungetc. Однако при каждом успешном вызове ungetwc для текстового или двоичного потока значение индикатора положения файла не определено до тех пор, пока все символы, отправленные обратно, не будут прочитаны или отменены.However, on each successful ungetwc call against a text or binary stream, the value of the file-position indicator is unspecified until all pushed-back characters are read or discarded.
Эти функции являются потокобезопасными и блокируют конфиденциальные данные во время выполнения.These functions are thread-safe and lock sensitive data during execution. Описание неблокирующей версии см. в разделе _ungetc_nolock, _ungetwc_nolock.For a non-locking version, see _ungetc_nolock, _ungetwc_nolock.
По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.
Универсальное текстовое сопоставление функцийGeneric-Text Routine Mappings
Подпрограмма TCHAR.HTCHAR.H routine | _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined | _MBCS определено_MBCS defined | _UNICODE определено_UNICODE defined |
---|---|---|---|
_ungettc_ungettc | ungetcungetc | ungetcungetc | ungetwcungetwc |
Remarks
The ungetc function pushes the character c back onto stream and clears the end-of-file indicator. The stream must be open for reading. A subsequent read operation on stream starts with c. An attempt to push EOF onto the stream using ungetc is ignored.
Characters placed on the stream by ungetc may be erased if fflush, fseek, fsetpos, or rewind is called before the character is read from the stream. The file-position indicator will have the value it had before the characters were pushed back. The external storage corresponding to the stream is unchanged. On a successful ungetc call against a text stream, the file-position indicator is unspecified until all the pushed-back characters are read or discarded. On each successful ungetc call against a binary stream, the file-position indicator is decremented; if its value was 0 before a call, the value is undefined after the call.
Results are unpredictable if ungetc is called twice without a read or file-positioning operation between the two calls. After a call to fscanf, a call to ungetc may fail unless another read operation (such as getc) has been performed. This is because fscanf itself calls ungetc.
ungetwc is a wide-character version of ungetc. However, on each successful ungetwc call against a text or binary stream, the value of the file-position indicator is unspecified until all pushed-back characters are read or discarded.
These functions are thread-safe and lock sensitive data during execution. For a non-locking version, see _ungetc_nolock, _ungetwc_nolock.
By default, this function’s global state is scoped to the application. To change this, see Global state in the CRT.
ТребованияRequirements
ПодпрограммаRoutine | Обязательный заголовокRequired header |
---|---|
ungetcungetc | <stdio.h><stdio.h> |
ungetwcungetwc | <stdio.h> или <wchar.h><stdio.h> or <wchar.h> |
Консоль не поддерживается в приложениях универсальная платформа Windows (UWP).The console is not supported in Universal Windows Platform (UWP) apps. Стандартные дескрипторы потока, связанные с консолью, stdin, stdoutи stderr, должны быть перенаправляться до того, как функции времени выполнения C смогут использовать их в приложениях UWP.The standard stream handles that are associated with the console, stdin, stdout, and stderr, must be redirected before C run-time functions can use them in UWP apps. Дополнительные сведения о совместимости см. в статье Compatibility.For additional compatibility information, see Compatibility.
Возвращаемое значениеReturn Value
В случае успеха каждая из этих функций Возвращает символьный аргумент c.If successful, each of these functions returns the character argument c. Если c не удается вернуть обратно или если ни один символ не был считан, входной поток не изменяется, а ungetc возвращает EOF; ungetwc возвращает WEOF.If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. Если Stream имеет значение NULL, вызывается обработчик недопустимых параметров, как описано в разделе Проверка параметров.If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. Если выполнение может быть продолжено, возвращается EOF или WEOF , а параметру «переводится » значение еинвал.If execution is allowed to continue, EOF or WEOF is returned and errno is set to EINVAL.
Дополнительные сведения об этих и других кодах ошибок см. в разделе _doserrno, errno, _sys_errlist и _sys_nerr.For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
RemarksRemarks
Каждая подпрограмма считывает один символ из файла в текущей позиции и увеличивает связанный указатель файла (если он определен), чтобы он указывал на следующий символ.Each routine reads a single character from a file at the current position and increments the associated file pointer (if defined) to point to the next character. Файл связан с потоком.The file is associated with stream.
Эти функции блокируют вызывающий поток, поэтому они потокобезопасны.These functions lock the calling thread and are therefore thread-safe. Описание неблокирующей версии см. в разделе _getc_nolock, _getwc_nolock.For a non-locking version, see _getc_nolock, _getwc_nolock.
Ниже приводятся примечания для конкретных подпрограмм.Routine-specific remarks follow.
ПодпрограммаRoutine | RemarksRemarks |
---|---|
getcgetc | То же, что и fgetc, но реализован как функция и как макрос.Same as fgetc, but implemented as a function and as a macro. |
getwcgetwc | Версия getcс расширенными символами.Wide-character version of getc. Считывает многобайтовый символ или широкий символ в зависимости от того, открыт ли поток в текстовом или двоичном режиме.Reads a multibyte character or a wide character according to whether stream is opened in text mode or binary mode. |
По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.
Универсальное текстовое сопоставление функцийGeneric-Text Routine Mappings
Подпрограмма TCHAR.HTCHAR.H routine | _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined | _MBCS определено_MBCS defined | _UNICODE определено_UNICODE defined |
---|---|---|---|
_gettc_gettc | getcgetc | getcgetc | getwcgetwc |
ТребованияRequirements
ПодпрограммаRoutine | Обязательный заголовокRequired header |
---|---|
gets_sgets_s | <stdio.h><stdio.h> |
_getws_s_getws_s | <stdio.h> или <wchar.h><stdio.h> or <wchar.h> |
Консоль не поддерживается в приложениях универсальная платформа Windows (UWP).The console is not supported in Universal Windows Platform (UWP) apps. Стандартные дескрипторы потока, связанные с консолью, stdin, stdoutи stderr, должны быть перенаправляться до того, как функции времени выполнения C смогут использовать их в приложениях UWP.The standard stream handles that are associated with the console, stdin, stdout, and stderr, must be redirected before C run-time functions can use them in UWP apps. Дополнительные сведения о совместимости см. в статье Compatibility.For additional compatibility information, see Compatibility.
ERRORS top
The fgetc() function shall fail if data needs to be read and: EAGAIN The O_NONBLOCK flag is set for the file descriptor underlying stream and the thread would be delayed in the fgetc() operation. EBADF The file descriptor underlying stream is not a valid file descriptor open for reading. EINTR The read operation was terminated due to the receipt of a signal, and no data was transferred. EIO A physical I/O error has occurred, or the process is in a background process group attempting to read from its controlling terminal, and either the calling thread is blocking SIGTTIN or the process is ignoring SIGTTIN or the process group of the process is orphaned. This error may also be generated for implementation-defined reasons. EOVERFLOW The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the corresponding stream. The fgetc() function may fail if: ENOMEM Insufficient storage space is available. ENXIO A request was made of a nonexistent device, or the request was outside the capabilities of the device. The following sections are informative.
傳回值Return Value
如果成功,所有這些函式都會傳回字元引數c。If successful, each of these functions returns the character argument c. 如果無法將c推送回來,或未讀取任何字元,則輸入資料流程不會變更,而且Ungetc會傳回EOF;ungetwc會傳回WEOF。If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. 如果stream為Null,則會叫用不正確參數處理常式,如參數驗證中所述。If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允許繼續執行,則會傳回EOF或WEOF ,並將errno設定為EINVAL。If execution is allowed to continue, EOF or WEOF is returned and errno is set to EINVAL.
如需這些錯誤碼和其他錯誤碼的資訊,請參閱 _doserrno、errno、_sys_errlist 和 _sys_nerr。For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
COPYRIGHT top
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, Copyright (C) 2013 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.unix.org/online.html . Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html . IEEE/The Open Group 2013 FGETC(3P)
Pages that refer to this page:
stdio.h(0p),
fgets(3p),
fread(3p),
fscanf(3p),
getc(3p),
getchar(3p),
getdelim(3p),
gets(3p)
КомментарииRemarks
Каждая подпрограммы считывает один символ из stdin и увеличивает связанный указатель файла, чтобы он указывал на следующий символ.Each routine reads a single character from stdin and increments the associated file pointer to point to the next character. Функция GetChars аналогична _fgetchar, но реализована в виде функции и макроса.getchar is the same as _fgetchar, but it’s implemented as a function and as a macro.
Эти функции также блокируют вызывающий поток и являются потокобезопасными.These functions also lock the calling thread and are thread-safe. Описание неблокирующей версии см. в разделе _getchar_nolock, _getwchar_nolock.For a non-locking version, see _getchar_nolock, _getwchar_nolock.
По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.
Универсальное текстовое сопоставление функцийGeneric-Text Routine Mappings
Подпрограмма TCHAR.HTCHAR.H routine | _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined | _MBCS определено_MBCS defined | _UNICODE определено_UNICODE defined |
---|---|---|---|
_gettchar_gettchar | getchargetchar | getchargetchar | getwchargetwchar |
Решение задач
Не смотря на свою кажущуюся примитивность, функции и часто используются, т.к. посимвольный анализ данных при вводе-выводе не такая уж редкая задача. Используя только функцию , можно получить массив символов (строку) и при этом отсеять ненужные символы. Вот пример помещения в строку только цифр из потока ввода, в котором может быть набран абсолютно любой символ:
#include <stdio.h> #define N 100 main () { char ch; char numsN; int i; i = ; while ((ch = getchar()) != EOF && i < N-1) if (ch >= 48 && ch <= 57) { numsi = ch; i++; } numsi = '\0'; printf("%s\n", nums); }
Здесь ввод символов может прекратиться не только при поступлении значения EOF, но и в случае, если массив заполнен (). В цикле проверяется условие, что числовой код очередного символа принадлежит диапазону . Именно в этом диапазоне кодируются цифры (0-9). Если поступивший символ является символом-цифрой, то он помещается в массив по индексу i, далее i увеличивается на 1, указывая на следующий элемент массива. После завершения цикла к массиву символов добавляется нулевой символ, т.к. по условию задачи должна быть получена строка (именно для этого символа ранее резервируется одна ячейка массива – ).
Задание
- Напишите программу, которая считает количество введенных пользователем символов и строк.
- Напишите программу, которая подсчитывает количество слов в строке.
DESCRIPTION top
The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard. If the end-of-file indicator for the input stream pointed to by stream is not set and a next byte is present, the fgetc() function shall obtain the next byte as an unsigned char converted to an int, from the input stream pointed to by stream, and advance the associated file position indicator for the stream (if defined). Since fgetc() operates on bytes, reading a character consisting of multiple bytes (or ``a multi-byte character'') may require multiple calls to fgetc(). The fgetc() function may mark the last data access timestamp of the file associated with stream for update. The last data access timestamp shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), fscanf(), getc(), getchar(), getdelim(), getline(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc().
返回值Return Value
如果成功,则每个函数将返回字符参数c。If successful, each of these functions returns the character argument c. 如果无法向后推送c ,或者未读取任何字符,则输入流将保持不变,并且ungetc返回EOF;ungetwc返回WEOF。If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. 如果stream为NULL,则会调用无效参数处理程序,如参数验证中所述。If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允许执行继续,则返回EOF或WEOF ,并将errno设置为EINVAL。If execution is allowed to continue, EOF or WEOF is returned and errno is set to EINVAL.
有关这些代码及其他错误代码的信息,请参阅 _doserrno、errno、_sys_errlist 和 _sys_nerr。For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
Функция языка Си scanf
Функция Си scanf () является более многогранной функцией, так как позволяет вводить в компьютер данные любых типов.
По аналогии с функцией printf() функция Си scanf() тоже может иметь несколько аргументов, позволяя тем самым вводить значения числовых, символьных и строковых переменных в одно и то же время.
Список параметров функции scanf() состоит из двух частей: строки формата и списка данных. В строке формата находятся указатели формата (преобразователи символов, после знака процента), которые определяют то, каким образом должны быть интерпретированы вводимые данные. Вторая часть функции — список данных, в котором перечисляются переменные, в которые должны быть занесены вводимые значения. Порядок следования указателей формата и переменных должен быть одинаков.
Указатели формата аналогичны тем, которые используются функцией .
Пример: функция scanf() вводит вещественное число и и присваивает его переменной amount (вносит его в область памяти, предназначенную для переменной)
main() { float amount; scanf("%f", &amount) } |
Показать аналог в Pascal
var amountreal; begin readln(amount) end. |
Важно: Когда компилятор доходит до функции scanf(), выполнение программы приостанавливается, и программа ожидает ввода данных. Как только будет нажата клавиши Enter, будет продолжено выполнение кода программы
Задание C 1_3_1: Объясните, почему следующая программа написана неправильно:
main() { char initial; initial = gets(); puts(initial); } |
Задание C 1_3_2: Напишите программу, которая выводит имя и возраст субъектов. Добавьте функцию printf(), которая выводила бы значения переменных:
... char name12; int age; ... |
Вопросы для самоконтроля:
Есть ли необходимость нажимать клавишу Enter после ввода с использованием функции getchar()?
Назовите два способа использования функции getchar().
Какие преимущества дает использование функции scanf()?
Функция языка Си gets
Ввод данных — это предоставление компьютеру информации, необходимой для работы программы. Вводимая информация присваивается переменным и хранится в памяти компьютера. В программе переменная используется в операциях и выражениях.
Функция Си gets() помещает в переменную вводимую строку. В качестве параметра функции указывается имя переменной, в которую и помещается строка.
Пример: в программе функция gets() рассматривает первые 14 символов (один элемент необходим для нулевого символа, поэтому в скобках следует указывать на один символ больше) и помещает введенную строку в переменную name; затем выводит ее значение на экран
main() { char name15; puts(“введите имя”); gets(name); puts(name); } |
Показать аналог в Pascal
var namestring; begin writeln('введите имя'); readln(name); writeln(name); end. |
返回值Return Value
如果成功,则每个函数将返回字符参数c。If successful, each of these functions returns the character argument c. 如果无法向后推送c ,或者未读取任何字符,则输入流将保持不变,并且ungetc返回EOF;ungetwc返回WEOF。If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. 如果stream为NULL,则会调用无效参数处理程序,如参数验证中所述。If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允许执行继续,则返回EOF或WEOF ,并将errno设置为EINVAL。If execution is allowed to continue, EOF or WEOF is returned and errno is set to EINVAL.
有关这些代码及其他错误代码的信息,请参阅 _doserrno、errno、_sys_errlist 和 _sys_nerr。For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
DESCRIPTION top
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once. getchar() is equivalent to getc(stdin). fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer. ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed. Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream. For nonlocking counterparts, see unlocked_stdio(3).
ТребованияRequirements
ПодпрограммаRoutine | Обязательный заголовокRequired header |
---|---|
getchargetchar | <stdio.h> |
getwchargetwchar | <stdio.h> или <wchar.h><stdio.h> or <wchar.h> |
Консоль не поддерживается в приложениях универсальная платформа Windows (UWP).The console isn’t supported in Universal Windows Platform (UWP) apps. Стандартные дескрипторы потока, связанные с консолью, stdin, stdoutи stderr, должны быть перенаправляться до того, как функции времени выполнения C смогут использовать их в приложениях UWP.The standard stream handles that are associated with the console, stdin, stdout, and stderr, must be redirected before C run-time functions can use them in UWP apps. Дополнительные сведения о совместимости см. в статье Compatibility.For additional compatibility information, see Compatibility.
备注Remarks
Ungetc函数将字符c推送到stream上,并清除文件尾指示符。The ungetc function pushes the character c back onto stream and clears the end-of-file indicator. 流必须打开以供读取。The stream must be open for reading. 对流的后续读取操作以c开头。A subsequent read operation on stream starts with c. 将忽略使用ungetc将EOF推送到流的尝试。An attempt to push EOF onto the stream using ungetc is ignored.
如果在从流中读取字符之前调用了fflush、 fseek、 fsetpos或倒带,则可能会清除ungetc上放置的字符。Characters placed on the stream by ungetc may be erased if fflush, fseek, fsetpos, or rewind is called before the character is read from the stream. 文件位置指示符将拥有将字符推送回之前的值。The file-position indicator will have the value it had before the characters were pushed back. 对应流的外部存储未改变。The external storage corresponding to the stream is unchanged. 对文本流进行成功的ungetc调用时,将不指定文件位置指示符,直到读取或丢弃所有推回的字符。On a successful ungetc call against a text stream, the file-position indicator is unspecified until all the pushed-back characters are read or discarded. 对于二进制流,每个成功的ungetc调用都将减少文件位置指示器;如果调用前其值为0,则调用后不定义该值。On each successful ungetc call against a binary stream, the file-position indicator is decremented; if its value was 0 before a call, the value is undefined after the call.
如果两次调用之间没有读取或文件定位操作 ,则结果是不可预知的。Results are unpredictable if ungetc is called twice without a read or file-positioning operation between the two calls. 调用fscanf后,对ungetc的调用可能会失败,除非已执行其他读取操作(例如getc)。After a call to fscanf, a call to ungetc may fail unless another read operation (such as getc) has been performed. 这是因为, fscanf本身调用了ungetc。This is because fscanf itself calls ungetc.
ungetwc是ungetc的宽字符版本。ungetwc is a wide-character version of ungetc. 但是,在每个针对文本或二进制流的成功ungetwc调用中,文件位置指示器的值是未指定的,直到读取或丢弃所有推送后的字符。However, on each successful ungetwc call against a text or binary stream, the value of the file-position indicator is unspecified until all pushed-back characters are read or discarded.
这些函数线程安全并会在执行期间锁定敏感数据。These functions are thread-safe and lock sensitive data during execution. 有关非锁定版本,请参阅 _ungetc_nolock、_ungetwc_nolock。For a non-locking version, see _ungetc_nolock, _ungetwc_nolock.
默认情况下,此函数的全局状态的作用域限定为应用程序。By default, this function’s global state is scoped to the application. 若要更改此项,请参阅CRT 中的全局状态。To change this, see Global state in the CRT.
一般文本例程映射Generic-Text Routine Mappings
TCHAR.H 例程TCHAR.H routine | 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined | 已定义 _MBCS_MBCS defined | 已定义 _UNICODE_UNICODE defined |
---|---|---|---|
_ungettc_ungettc | ungetcungetc | ungetcungetc | ungetwcungetwc |
Description
Standard I/O Routines perform input and output operations on files.
Input and Output operations are performed in C using the Standard Input and Output Library (stdio.h). This library uses streams to operate with physical devices such as keyboards, printers, terminals or with any other type of files supported by the system. Streams are used to interact with all these devices in the same way. All streams share similar properties, regardless of the physical media they are associated with.
In the stdio library, all streams are defined as pointers to FILE objects, being used as a parameter in the operations involving the stream.
Three standard streams are available: stdin, stdout and stderr. They are automatically being created and opened for all programs using the stdio library.