freopen_s、_wfreopen_sfreopen_s, _wfreopen_s

重新分配文件指针。Reassigns a file pointer. 这些版本的 freopen、_wfreopen 具有安全增强功能,如 CRT 中的安全功能所述。These versions of freopen, _wfreopen have security enhancements, as described in Security Features in the CRT.

语法Syntax

errno_t freopen(
   FILE** pFile,
   const char *path,
   const char *mode,
   FILE *stream
);
errno_t _wfreopen(
   FILE** pFile,
   const wchar_t *path,
   const wchar_t *mode,
   FILE *stream
);

参数Parameters

pFilepFile
一个指针,指向由调用提供的文件指针。A pointer to the file pointer to be provided by the call.

pathpath
新文件的路径。Path of new file.

模式mode
允许的访问类型。Type of access permitted.

streamstream
指向文件结构的指针。Pointer to FILE structure.

返回值Return Value

其中每个函数会返回一个错误代码。Each of these functions returns an error code. 如果发生错误,则关闭原始文件。If an error occurs, the original file is closed.

备注Remarks

Freopen_s函数关闭当前与stream关联的文件,并将重新分配到path指定的文件。The freopen_s function closes the file currently associated with stream and reassigns stream to the file specified by path. _wfreopen_s_freopen_s的宽字符版本; _wfreopen_s路径模式参数是宽字符字符串。_wfreopen_s is a wide-character version of _freopen_s; the path and mode arguments to _wfreopen_s are wide-character strings. 否则, _wfreopen_s_freopen_s的行为相同。_wfreopen_s and _freopen_s behave identically otherwise.

如果任何 .pfilepathmodestreamNULL, 或者如果path为空字符串, 则这些函数将调用无效参数处理程序, 如参数验证中所述。If any of pFile, path, mode, or stream are NULL, or if path is an empty string, these functions invoke the invalid parameter handler, as described in Parameter Validation. 如果允许执行继续, 则这些函数会将errno设置为EINVAL并返回EINVALIf execution is allowed to continue, these functions set errno to EINVAL and return EINVAL.

一般文本例程映射Generic-Text Routine Mappings

TCHAR.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_tfreopen_s_tfreopen_s freopen_sfreopen_s freopen_sfreopen_s _wfreopen_s_wfreopen_s

freopen_s通常用于将预先打开的文件stdinstdoutstderr重定向到用户指定的文件。freopen_s is typically used to redirect the pre-opened files stdin, stdout, and stderr to files specified by the user. stream关联的新文件以模式打开, 该模式是指定文件请求的访问类型的字符串, 如下所示:The new file associated with stream is opened with mode, which is a character string specifying the type of access requested for the file, as follows:

模式mode AccessAccess
“r”"r" 打开以便读取。Opens for reading. 如果文件不存在或找不到,则freopen_s调用失败。If the file does not exist or cannot be found, the freopen_s call fails.
“w”"w" 打开用于写入的空文件。Opens an empty file for writing. 如果给定文件存在,则其内容会被销毁。If the given file exists, its contents are destroyed.
“a”"a" 在文件末尾打开以进行写入(追加),在新数据写入到文件之前不移除文件末尾 (EOF) 标记。Opens for writing at the end of the file (appending) without removing the end-of-file (EOF) marker before new data is written to the file. 创建文件(如果文件不存在)。Creates the file if it does not exist.
“r+”"r+" 打开以便读取和写入。Opens for both reading and writing. 文件必须存在。The file must exist.
“w+”"w+" 打开用于读取和写入的空文件。Opens an empty file for both reading and writing. 如果文件存在,则其内容会被销毁。If the file exists, its contents are destroyed.
“a+”"a+" 打开以进行读取和追加。Opens for reading and appending. 追加操作包括在新数据写入文件之前移除 EOF 标记。The appending operation includes the removal of the EOF marker before new data is written to the file. 写入完成后,EOF 标记不会还原。The EOF marker is not restored after writing is completed. 创建文件(如果文件不存在)。Creates the file if it does not exist.

使用 "w""w +" 类型时要小心, 因为它们可能会破坏现有文件。Use the "w" and "w+" types with care, as they can destroy existing files.

使用 "a""a +" 访问类型打开文件时, 所有写入操作都将在文件末尾进行。When a file is opened with the "a" or "a+" access type, all write operations take place at the end of the file. 尽管可以使用fseek倒带重定位文件指针, 但在执行任何写入操作前, 文件指针将始终被移回文件末尾。因此,无法覆盖现有数据。Although the file pointer can be repositioned using fseek or rewind, the file pointer is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.

"A" 模式不会在追加到文件之前删除 EOF 标记。The "a" mode does not remove the EOF marker before appending to the file. 在追加后,MS-DOS TYPE 命令只显示原始 EOF 标记之前的数据,不显示追加到文件的任何数据。After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data appended to the file. "A +" 模式将在追加到文件之前删除 EOF 标记。The "a+" mode does remove the EOF marker before appending to the file. 在追加后,MS-DOS TYPE 命令显示文件中的所有数据。After appending, the MS-DOS TYPE command shows all data in the file. 附加到使用 CTRL + Z EOF 标记终止的流文件需要 "a +" 模式。The "a+" mode is required for appending to a stream file that is terminated with the CTRL+Z EOF marker.

指定 "r +""w +""a +" 访问类型时, 允许读取和写入 (文件称为 "更新")。When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). 但是,在读取与写入之间切换时,必须有干预性的 fsetposfseekrewind 操作。However, when you switch between reading and writing, there must be an intervening fsetpos, fseek, or rewind operation. 如果需要, 可以为fsetposfseek操作指定当前位置。The current position can be specified for the fsetpos or fseek operation, if desired. 除了以上值之外,模式字符串中还可能会包含以下字符之一以指定新行的转换模式。In addition to the above values, one of the following characters may be included in the mode string to specify the translation mode for new lines.

模式修饰符mode modifier 转换模式Translation mode
tt 在文本(转换)模式下打开。Open in text (translated) mode.
bb 在二进制 (未转换) 模式下打开;将禁止涉及回车符和换行符的翻译。Open in binary (untranslated) mode; translations involving carriage-return and line feed characters are suppressed.

在文本 (已转换) 模式下, 回车换行符 (CR-LF) 组合将转换为输入的单行换行符 (LF) 字符;换行符在输出时转换为 CR-LF 组合。In text (translated) mode, carriage return-line feed (CR-LF) combinations are translated into single line feed (LF) characters on input; LF characters are translated to CR-LF combinations on output. CTRL+Z 也将在输入时解释为文件尾字符。Also, CTRL+Z is interpreted as an end-of-file character on input. 在打开以进行读取或使用 "a +" 进行读取和读取的文件中, 运行时库将检查文件末尾的 CTRL + Z 并将其删除 (如果可能)。In files opened for reading or for writing and reading with "a+", the run-time library checks for a CTRL+Z at the end of the file and removes it, if possible. 这样做的原因是, 使用fseekftell在文件中移动可能导致fseek在文件结尾附近出现错误。This is done because using fseek and ftell to move within a file may cause fseek to behave improperly near the end of the file. T选项是一个 Microsoft 扩展, 不应在需要 ANSI 可移植性时使用。The t option is a Microsoft extension that should not be used where ANSI portability is desired.

如果在mode中未给出tb ,则默认转换模式由全局变量_fmode定义。If t or b is not given in mode, the default translation mode is defined by the global variable _fmode. 如果tb作为参数的前缀, 则函数将失败并返回NULLIf t or b is prefixed to the argument, the function fails and returns NULL.

有关文本模式和二进制模式的讨论,请参阅文本和二进制模式文件 I/OFor a discussion of text and binary modes, see Text and Binary Mode File I/O.

要求Requirements

函数Function 必需的标头Required header
freopen_sfreopen_s <stdio.h><stdio.h>
_wfreopen_s_wfreopen_s <stdio.h> 或 <wchar.h><stdio.h> or <wchar.h>

通用 Windows 平台 (UWP) 应用中不支持控制台。The console is not supported in Universal Windows Platform (UWP) apps. 与控制台、 stdinstdoutstderr关联的标准流句柄必须重定向, 然后 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. 有关其他兼容性信息,请参阅 兼容性For additional compatibility information, see Compatibility.

示例Example

// crt_freopen_s.c
// This program reassigns stderr to the file
// named FREOPEN.OUT and writes a line to that file.

#include <stdio.h>
#include <stdlib.h>

FILE *stream;

int main( void )
{
   errno_t err;
   // Reassign "stderr" to "freopen.out":
   err = freopen_s( &stream, "freopen.out", "w", stderr );

   if( err != 0 )
      fprintf( stdout, "error on freopen\n" );
   else
   {
      fprintf( stdout, "successfully reassigned\n" ); fflush( stdout );
      fprintf( stream, "This will go to the file 'freopen.out'\n" );
      fclose( stream );
   }
   system( "type freopen.out" );
}
successfully reassigned
This will go to the file 'freopen.out'

请参阅See also

流 I/OStream I/O
freopen、_wfreopenfreopen, _wfreopen
fclose、_fcloseallfclose, _fcloseall
_fdopen、_wfdopen_fdopen, _wfdopen
_fileno_fileno
fopen、_wfopen_wfopenfopen, _wfopen
_open、_wopen_open, _wopen
_setmode_setmode