Fputc in c programming

Dönüş DeğeriReturn Value

Bu işlevlerin her biri yazılan karakteri döndürür.Each of these functions returns the character written. FputcIçin, EOF dönüş değeri bir hatayı gösterir.For fputc, a return value of EOF indicates an error. FputwcIçin, weof ‘ın dönüş değeri bir hatayı gösterir.For fputwc, a return value of WEOF indicates an error. Stream nullIse, bu işlevler parametre doğrulamabölümünde açıklandığı gibi geçersiz parametre işleyicisini çağırır.If stream is NULL, these functions invoke the invalid parameter handler, as described in Parameter Validation. Yürütmenin devam etmesine izin veriliyorsa, EOF döndürür ve errno , EINVALolarak ayarlanır.If execution is allowed to continue, they return EOF and set errno to EINVAL.

Bu ve diğer hata kodları hakkında daha fazla bilgi için bkz. _doserrno, errno, _sys_errlist ve _sys_nerr .See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes.

ТребованияRequirements

ПодпрограммаRoutine Обязательный заголовокRequired header
putcharputchar <stdio.h><stdio.h>
putwcharputwchar <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.

RemarksRemarks

Каждая из этих функций записывает один символ c в файл в позиции, указанной соответствующим индикатором позиции файла (если он определен), и перемещает индикатор соответствующим образом.Each of these functions writes the single character c to a file at the position indicated by the associated file position indicator (if defined) and advances the indicator as appropriate. В случае с fputc и fputwcфайл связан с потоком.In the case of fputc and fputwc, the file is associated with stream. Если файл не поддерживает запросы позиционирования или был открыт в режиме добавления, символ добавляется в конец потока.If the file cannot support positioning requests or was opened in append mode, the character is appended to the end of the stream.

Эти две функции ведут себя одинаково, если поток открыт в режиме ANSI.The two functions behave identically if the stream is opened in ANSI mode. fputc в настоящее время не поддерживает вывод в поток Юникода.fputc does not currently support output into a UNICODE stream.

Версии с суффиксом _nolock идентичны за исключением того, что они не защищены от помех со стороны других потоков.The versions with the _nolock suffix are identical except that they are not protected from interference by other threads. Дополнительные сведения см. в разделе _fputc_nolock, _fputwc_nolock.For more information, see_fputc_nolock, _fputwc_nolock.

Ниже приводятся примечания для конкретных подпрограмм.Routine-specific remarks follow.

ПодпрограммаRoutine RemarksRemarks
fputcfputc Эквивалентно putc, но реализован только как функция, а не как функция и макрос.Equivalent to putc, but implemented only as a function, rather than as a function and a macro.
fputwcfputwc Версия fputcс расширенными символами.Wide-character version of fputc. Записывает c в виде многобайтового символа или расширенного символа в зависимости от того, открыт ли поток в текстовом или двоичном режиме.Writes c as 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
_fputtc_fputtc fputcfputc fputcfputc fputwcfputwc

GereksinimlerRequirements

İşlevFunction Gerekli başlıkRequired header
fputcfputc <stdio. h><stdio.h>
fputwcfputwc <stdio. h> veya <wchar. h><stdio.h> or <wchar.h>

Konsol Evrensel Windows Platformu (UWP) uygulamalarında desteklenmez.The console is not supported in Universal Windows Platform (UWP) apps. Bu konsol ile ilişkili standart akış tutamaçları (stdin, stdoutve stderr), C çalışma zamanı işlevlerinin bunları UWP uygulamalarında kullanabilmesi için yeniden yönlendirilmelidir.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. Ek uyumluluk bilgileri için bkz. Uyumluluk.For additional compatibility information, see Compatibility.

备注Remarks

其中每个函数将单个字符c写入到文件位置指示符指示的位置(如果已定义),并根据需要提升指示器。Each of these functions writes the single character c to a file at the position indicated by the associated file position indicator (if defined) and advances the indicator as appropriate. 对于fputc和fputwc,该文件与stream关联。In the case of fputc and fputwc, the file is associated with stream. 如果文件不支持定位请求,或在追加模式中打开,则该字符将被追加到流的末尾。If the file cannot support positioning requests or was opened in append mode, the character is appended to the end of the stream.

如果在 ANSI 模式下打开流,则这两个函数行为相同。The two functions behave identically if the stream is opened in ANSI mode. fputc当前不支持输出到 UNICODE 流中。fputc does not currently support output into a UNICODE stream.

后缀为 _nolock 的版本是相同的,只不过它们可能会受到其他线程的影响。The versions with the _nolock suffix are identical except that they are not protected from interference by other threads. 有关详细信息,请参阅 _fputc_nolock、_fputwc_nolock。For more information, see_fputc_nolock, _fputwc_nolock.

下面是例程特定的备注。Routine-specific remarks follow.

例程Routine 备注Remarks
fputcfputc 等效于putc,但仅作为函数实现,而不是作为函数和宏实现。Equivalent to putc, but implemented only as a function, rather than as a function and a macro.
fputwcfputwc Fputc的宽字符版本。Wide-character version of fputc. 根据流是在文本模式还是二进制模式中打开,将c写入多字节字符或宽字符。Writes c as 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.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_fputtc_fputtc fputcfputc fputcfputc fputwcfputwc

AçıklamalarRemarks

Bu işlevlerin her biri, tek bir c karakterini ilişkili dosya konumu göstergesi (tanımlanmışsa) tarafından belirtilen konumdaki bir dosyaya yazar ve göstergeyi uygun şekilde ilerletir.Each of these functions writes the single character c to a file at the position indicated by the associated file position indicator (if defined) and advances the indicator as appropriate. Fputc ve fputwcdurumunda, dosya Streamile ilişkilendirilir.In the case of fputc and fputwc, the file is associated with stream. Dosya konumlandırma isteklerini desteklemez veya ekleme modunda açıldıysa, karakter akışın sonuna eklenir.If the file cannot support positioning requests or was opened in append mode, the character is appended to the end of the stream.

Akış ANSI modunda açılırsa iki işlev aynı şekilde davranır.The two functions behave identically if the stream is opened in ANSI mode. fputc Şu anda bir UNICODE akışına çıktıyı desteklemiyor.fputc does not currently support output into a UNICODE stream.

_Nolock sonekine sahip sürümler, diğer iş parçacıkları tarafından girişime karşı korunmamaları dışında aynıdır.The versions with the _nolock suffix are identical except that they are not protected from interference by other threads. Daha fazla bilgi için bkz._fputc_nolock, _fputwc_nolock.For more information, see_fputc_nolock, _fputwc_nolock.

Rutin olarak özgü notlar izler.Routine-specific remarks follow.

YordamRoutine AçıklamalarRemarks
fputcfputc Putcile eşdeğerdir, ancak bir işlev ve makro olarak değil, yalnızca işlev olarak uygulanır.Equivalent to putc, but implemented only as a function, rather than as a function and a macro.
fputwcfputwc Fputc’nin geniş karakterli sürümü.Wide-character version of fputc. Akış metin modunda veya ikili modda açılıp açılmayacağı için çok baytlı bir karakter veya geniş karakter olarak c yazar.Writes c as a multibyte character or a wide character according to whether stream is opened in text mode or binary mode.

Varsayılan olarak, bu işlevin genel durumu uygulamanın kapsamına alınır.By default, this function’s global state is scoped to the application. Bunu değiştirmek için bkz. CRT Içindeki genel durum.To change this, see Global state in the CRT.

Genel Metin Yordam EşleşmeleriGeneric-Text Routine Mappings

TCHAR.H yordamıTCHAR.H routine _UNICODE & _MBCS tanımlanmadı_UNICODE & _MBCS not defined _MBCS tanımlanmış_MBCS defined _UNICODE tanımlanmış_UNICODE defined
_fputtc_fputtc fputcfputc fputcfputc fputwcfputwc

返回值Return Value

其中每个函数都会返回写入的字符。Each of these functions returns the character written. 对于fputc,返回值EOF表示错误。For fputc, a return value of EOF indicates an error. 对于fputwc, WEOF的返回值指示错误。For fputwc, a return value of WEOF indicates an error. 如果stream为NULL,则这些函数将调用无效参数处理程序,如参数验证中所述。If stream is NULL, these functions invoke the invalid parameter handler, as described in Parameter Validation. 如果允许执行继续,则它们将返回EOF ,并将Errno设置为EINVAL。If execution is allowed to continue, they return EOF and set errno to EINVAL.

有关这些代码以及其他错误代码的详细信息,请参阅 _doserrno、errno、_sys_errlist 和 _sys_nerr。See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes.

Связь с консольным вводом / выводом

В языке С консольный и файловый ввод/вывод не слишком отличаются друг от друга. Функции консольного ввода/вывода, описанные в главе 8, на самом деле направляют результаты своих операций на один из потоков — stdin или stdout, и по сути, каждая из них является специальной версией соответствующей файловой функции. Функции консольного ввода/вывода для того и существуют, чтобы было удобно именно программисту.

Как говорилось в предыдущем разделе, ввод/вывод на консоль можно выполнять с помощью любой файловой функции языка С. Однако для вас может быть сюрпризом, что, оказывается, операции ввода/вывода на дисковых файлах можно выполнять с помощью функции консольного ввода/вывода, например, printf()! Дело в том, что все функции консольного ввода/вывода, о которых говорилось в главе 8, выполняют свои операции с потоками stdin и stdout. В средах, поддерживающих перенаправление ввода/вывода, это равносильно тому, что stdin или stdout могут быть перенаправлены на устройство, отличное от клавиатуры или экрана. Проанализируйте, например, следующую программу:

#include <stdio.h>

int main(void)
{
  char str;

  printf("Введите строку: ");
  gets(str);
  printf(str);

  return 0;
}

Предположим, что эта программа называется TEST. При ее нормальном выполнении на экран выводится подсказка, затем читается строка, введенная с клавиатуры, и, наконец, эта строка выводится на экран. Однако в средах, в которых поддерживается перенаправление ввода/вывода, один из потоков stdin или stdout (или оба одновременно) можно перенаправить в файл. Например, в среде DOS или Windows следующий запуск TEST

TEST > OUTPUT

приводит к тому, что вывод этой программы будет записан в файл по имени OUTPUT. А следующий запуск TEST

TEST < INPUT > OUTPUT

направляет поток stdin в файл по имени INPUT, а поток стандартного вывода — в файл по имени OUTPUT.

Когда С-программа завершается, то все перенаправленные потоки возвращаются в состояния, которые были установлены по умолчанию.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector