
fopen函数的用法示例
In C and C++ programming languages fopen()
function is used to open files and make operations like add, update, create for data. In this tutorial we will learn the syntax, usage and errors about the fopen()
function.
在C和C ++编程语言中, fopen()
函数用于打开文件并进行诸如添加,更新和创建数据之类的操作。 在本教程中,我们将学习有关fopen()
函数的语法,用法和错误。
fopen()函数语法 (fopen() Function Syntax)
fopen()
function is provided by the standard C library. The fopen() function has the following syntax.
fopen()
函数由标准C库提供。 fopen()函数具有以下语法。
FILE *fopen(const char *FILENAME, const char *MODE)
- `FILE *` is the return type of the fopen() function which is a pointer to a FILE structure. This file pointer is used for operations to add, update, etc. FILE *是fopen()函数的返回类型,它是指向FILE结构的指针。 该文件指针用于添加,更新等操作。
- `const char *FILENAME` is simply the file name that will be opened by fopen() function. `const char * FILENAME`只是将由fopen()函数打开的文件名。
- `const char *MODE` is the file open mode that will set the behavior of the file operations like only read, write, append, etc. const char * MODE是文件打开模式,它将设置文件操作的行为,例如仅读,写,追加等。
The fopen() function will return a FILE pointer to the opened file in successful execution. If there is error the return value will be NULL and the global variable errno
will be set for the related error.
fopen()函数将在成功执行后返回指向已打开文件的FILE指针。 如果存在错误,则返回值将为NULL,并且将为相关错误设置全局变量errno
。
文件打开模式 (File Open Modes)
Before starting the examples of the fopen() function we will learn file open modes. File open modes sets and restrict file access type like only read, update, create the file if do not exists, etc. File modes are represented as characters and + sign.
在开始fopen()函数的示例之前,我们将学习文件打开模式。 文件打开模式设置和限制文件访问类型,例如仅读取,更新,创建文件(如果不存在)等。文件模式表示为字符和+号。
- `”r”` is used as the file for reading. This will open the file as read-only and the file cannot be edited in this mode. As expected the file should exist where it will not be created automatically. “ r”用作读取文件。 这将以只读方式打开文件,并且在此模式下无法编辑文件。 如预期的那样,该文件应存在于不会自动创建的位置。
- `”w”` will create an empty file for writing. If the file already exists the existing file will be deleted or erased and the new empty file will be used. Be cautious while using these options. “” w”将创建一个用于写入的空文件。 如果文件已存在,则将删除或删除现有文件,并使用新的空文件。 使用这些选项时要小心。
- `”a”` is used for appending new data into the specified file. The file will be created if it doesn’t exist. “ a”用于将新数据附加到指定文件中。 如果该文件不存在,则将创建该文件。
- `”r+”` mode will open the file to update which will provide read and write rights. But the file must already exist if not it will not be created and throw an error. “ r +”模式将打开要更新的文件,该文件将提供读写权限。 但是文件必须已经存在,否则将无法创建并抛出错误。
- `”w+”` will create an empty file for both reading and writing. “” w +”`将创建一个用于读取和写入的空文件。
- `”a+”` will open a file for reading and appending.