C++文件相关操作

来源:互联网 发布:mac ps破解版安装教程 编辑:程序博客网 时间:2024/06/11 22:03

整理了一下系统中与文件操作相关的函数及数据结构

fopen,fclose,fseek,fread,fwrite

FILE,size_t

 

fopen

function
<cstdio>
FILE * fopen ( const char * filename, const char * mode );

Open file

Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE object whose pointer is returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter.
The running environment supports at least FOPEN_MAX files open simultaneously; FOPEN_MAX is a macro constant defined in <cstdio>.

Parameters

filename
C string containing the name of the file to be opened. This paramenter must follow the file name specifications of the running environment and can include a path if the system supports it.
mode
C string containing a file access modes. It can be:
"r"Open a file for reading. The file must exist."w"Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a"Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist."r+"Open a file for update both reading and writing. The file must exist."w+"Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file."a+"Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
Additional characters may follow the sequence, although they should have no effect. For example, "t" is sometimes appended to make explicit the file is a text file.
In the case of text files, depending on the environment where the application runs, some special character conversion may occur in input/output operations to adapt them to a system-specific text file format. In many environments, such as most UNIX-based systems, it makes no difference to open a file as a text file or a binary file; Both are treated exactly the same way, but differentiation is recommended for a better portability.
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

Return Value

If the file has been succesfully opened the function will return a pointer to a FILE object that is used to identify the stream on all further operations involving it. Otherwise, a null pointer is returned.
 
 

fclose


function
<cstdio>
int fclose ( FILE * stream );

Close file

Closes the file associated with the stream and disassociates it.
All internal buffers associated with the stream are flushed: the content of any unwritten buffer is written and the content of any unread buffer is discarded.
Even if the call fails, the stream passed as parameter will no longer be associated with the file.

Parameters

stream
Pointer to a FILE object that specifies the stream to be closed.


Return Value

If the stream is successfully closed, a zero value is returned.
On failure, EOF is returned.
 
 

fseek


function
<cstdio>
int fseek ( FILE * stream, long int offset, int origin );

Reposition stream position indicator

Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin.
The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped.
When using fseek on text files with offset values other than zero or values retrieved with ftell, bear in mind that on some platforms some format transformations occur with text files which can lead to unexpected repositioning.
On streams open for update (read+write), a call to fseek allows to switch between reading and writing.

Parameters

stream
Pointer to a FILE object that identifies the stream.
offset
Number of bytes to offset from origin.
origin
Position from where offset is added. It is specified by one of the following constants defined in <cstdio>:
SEEK_SETBeginning of fileSEEK_CURCurrent position of the file pointerSEEK_ENDEnd of file


Return Value

If successful, the function returns a zero value.
Otherwise, it returns nonzero value.
 

fread


function
<cstdio>
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Read block of data from stream

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.
The postion indicator of the stream is advanced by the total amount of bytes read.
The total amount of bytes read if successful is (size * count).

Parameters

ptr
Pointer to a block of memory with a minimum size of (size*count) bytes.
size
Size in bytes of each element to be read.
count
Number of elements, each one with a size of size bytes.
stream
Pointer to a FILE object that specifies an input stream.


Return Value

The total number of elements successfully read is returned as a size_t object, which is an integral data type.
If this number differs from the count parameter, either an error occured or the End Of File was reached.
You can use either ferror or feof to check whether an error happened or the End-of-File was reached.
 
 

fwrite


function
<cstdio>
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

Write block of data to stream

Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream.
The postion indicator of the stream is advanced by the total number of bytes written.
The total amount of bytes written is (size * count).

Parameters

ptr
Pointer to the array of elements to be written.
size
Size in bytes of each element to be written.
count
Number of elements, each one with a size of size bytes.
stream
Pointer to a FILE object that specifies an output stream.


Return Value

The total number of elements successfully written is returned as a size_t object, which is an integral data type.
If this number differs from the count parameter, it indicates an error.
 
 

FILE


type
<cstdio>

Object containing information to control a stream

This type of object identifies a stream and contains the information needed to control it, including a pointer to its buffer, its position indicator and all its state indicators.

FILE objects are usually created by a call to either fopen or tmpfile, which both return a reference to one of these objects.
The content of a FILE object is not meant to be read from outside the functions of the cstdio library; In fact, its main purpose is to be referenced as an argument in all stream-involving functions of this library to identify the stream to be affected.
Its memory allocation is automatically performed by either fopen or tmpfile, and is the responsibility of the library to free the resources once the stream has been closed using fclose or other means.
On inclusion of the cstdio header file, three objects of type FILE * (pointer to FILE)are automatically created. These are associated with the standard input, output and error streams, and can be accessed respectively through the pointers stdin, stdout and stderr.

typedef struct  {
        short           level;          /* fill/empty level of buffer */
        unsigned        flags;          /* File status flags    */
        char            fd;             /* File descriptor      */
        unsigned char   hold;           /* Ungetc char if no buffer */
        short           bsize;          /* Buffer size          */
        unsigned char   *buffer;        /* Data transfer buffer */
        unsigned char   *curp;          /* Current active pointer */
        unsigned        istemp;         /* Temporary file indicator */
        short           token;          /* Used for validity checking */
}       FILE;                           /* This is the FILE object */

size_t


type
<cstddef>

Unsigned integral type

size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the <cstddef> header file (among others) as an unsigned integral type.

It expresses a size or count in bytes.
 
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 印花t恤图案掉了怎么办 衣服上印花掉了怎么办 ps cs 3图标太小怎么办 ai cs6图标太小怎么办 su界面太小怎么办win10 华为p9手机gps信号弱怎么办 小米手机导航gps信号弱怎么办 安卓手机gps信号弱怎么办 苹果6导航gps信号弱怎么办 苹果6plus反应慢怎么办 手机文件打开是乱码怎么办 手机wps文件打开是乱码怎么办 腾讯视频vip账号被盗怎么办 附单据数错了 怎么办 橡胶的回弹性差怎么办 自己喷漆喷坏了怎么办 透明塑料磨花了怎么办 包包金属刮花了怎么办 鞋子刮了黑印子怎么办 黑色鞋跟磨白了怎么办 脚穿鞋子磨起泡怎么办 脚被鞋子磨红了怎么办 脚被鞋子磨黑了怎么办 白鞋皮鞋磨了皮怎么办 小脚趾磨肿了怎么办 穿鞋小拇指磨脚怎么办 高铁东西忘了怎么办 人故意去撞车死了怎么办? 新货车上户超重怎么办 车险出保单车号填错怎么办 货车拦板变形了怎么办 行车监控看不清楚车号怎么办? 1.5米的鱼缸要怎么办 被锤子砸到手了怎么办 家里地下污水管道堵塞怎么办 家里pvc灯罩变黄怎么办 欧普吸顶灯灯罩坏了怎么办 硬盘用久了变慢怎么办 地税申报工资人员弄错怎么办 买保险保单丢了怎么办 买保险的银行卡丢了怎么办