文件和流Files and Streams

程序通过读取和写入文件来与目标环境进行通信。A program communicates with the target environment by reading and writing files. 文件可以是:A file can be:

  • 可重复读取和写入的数据集。A data set that you can read and write repeatedly.

  • 程序生成的字节流(如管线)。A stream of bytes generated by a program (such as a pipeline).

  • 从外围设备接收或发送到外围设备的字节流。A stream of bytes received from or sent to a peripheral device.

    最后两项是交互式文件。The last two items are interactive files. 文件通常是用来与程序进行交互的主要手段。Files are typically the principal means by which to interact with a program. 您操作所有此类文件的方式与调用库函数的方式极为相似。You manipulate all these kinds of files in much the same way — by calling library functions. 您包括标准标头 STDIO.H 来声明其中的大多数函数。You include the standard header STDIO.H to declare most of these functions.

    必须先打开文件,然后才能对该文件执行许多操作。Before you can perform many of the operations on a file, the file must be opened. 打开文件会将其与流、标准 C 库(屏蔽了各种文件之间的许多差异)中的数据结构关联。Opening a file associates it with a stream, a data structure within the Standard C Library that glosses over many differences among files of various kinds. 库将维护类型 FILE 的对象中的每个流的状态。The library maintains the state of each stream in an object of type FILE.

    在程序启动前,目标环境将打开三个文件。The target environment opens three files before program startup. 可通过将库函数 fopen、_wfopen 与两个参数一起调用来打开文件。You can open a file by calling the library function fopen, _wfopen with two arguments. fopen 函数已弃用,请改用 fopen_s、_wfopen_s。)第一个自变量是文件名。(The fopen function has been deprecated, use fopen_s, _wfopen_s instead.) The first argument is a filename. 第二个参数是指定以下内容的 C 字符串:The second argument is a C string that specifies:

  • 您是否想从该文件中读取数据和/或将数据写入该文件中。Whether you intend to read data from the file or write data to it or both.

  • 您是想为文件生成新内容(或创建文件,如果文件之前不存在)还是保留现有内容。Whether you intend to generate new contents for the file (or create a file if it did not previously exist) or leave the existing contents in place.

  • 对文件进行写入是否可更改现有内容还是只应在文件尾追加字节。Whether writes to a file can alter existing contents or should only append bytes at the end of the file.

  • 您是要操作文本流还是二进制流。Whether you want to manipulate a text stream or a binary stream.

    一旦成功打开此文件,您就可以确定此流是面向字节的(字节流)还是面向宽度的(宽度流)。Once the file is successfully opened, you can then determine whether the stream is byte oriented (a byte stream) or wide oriented (a wide stream). 最初,流处于未绑定状态。A stream is initially unbound. 调用要对流使用的特定函数可使流成为面向字节的流,而其他函数可使流成为面向宽度的流。Calling certain functions to operate on the stream makes it byte oriented, while certain other functions make it wide oriented. 在建立流后,它将维护自己的方向,直至通过调用 fclosefreopen 将其关闭。Once established, a stream maintains its orientation until it is closed by a call to fclose or freopen.

    © 1989-2001(由 P.J.© 1989-2001 by P.J. Plauger 和 Jim Brodie 撰写)。Plauger and Jim Brodie. 保留所有权利。All rights reserved.

请参阅See Also

文本和二进制流 Text and Binary Streams
字节和宽流 Byte and Wide Streams
控制流 Controlling Streams
流状态Stream States