C/C++ 标准 I/O 中的打开模式及示例
先决条件:C++ 中的文件处理
到目前为止,使用 C 程序的操作是在未存储在任何地方的提示符/终端上完成的。但是在软件行业,大多数程序都是为了存储从程序中获取的信息而编写的。一种这样的方法是将获取的信息存储在文件中。可以对文件执行的不同操作包括:
- 创建一个新文件(fopen,属性为“a”或“a+”或“w”或“w++”)。
- 打开现有文件(fopen)。
- 从文件中读取(fscanf 或 fgets)。
- 写入文件(fprintf 或 fputs)。
- 移动到文件中的特定位置(fseek、rewind)。
- 关闭文件(fclose)。
括号中的文字表示用于执行这些操作的函数。
为什么需要文件?
- 数据保存:即使程序终止,将数据存储在文件中也有助于保存数据。
- 轻松访问数据:当数据量很大并且存储在文件中时,访问数据变得容易,然后可以使用C命令访问这些数据。
- 可移植性:无需任何更改即可将数据从一台计算机移动到另一台计算机变得更容易。
文件类型
它们是每个人都应该注意的两种类型的文件-
- 文本文件:文本文件是文件名中带有扩展名“.txt”的普通文件。这些可以使用记事本等编辑器轻松创建。打开文件后,文本将显示为简单的纯文本,并且可以轻松编辑或删除内容。这些是最低维护文件,易于阅读。但是文本文件有一些缺点,比如它们是最不安全的文件并且占用更大的存储空间。
- 二进制文件:二进制文件是“.bin”扩展名文件。这些文件中的数据以二进制形式存储,即 0 和 1。这些文件可以保存大量数据并提供比文本文件更高级别的安全性,但这些文件不易读取。
文件操作
可以对文件执行四种基本操作:
- 创建一个新文件。
- 打开现有文件。
- 从文件中读取或写入信息。
- 关闭文件。
处理文件
处理文件时,需要声明文件类型的指针。文件和程序之间的通信需要此文件类型指针。
File *fptr;
打开文件
使用头文件 stdio.h 中的 fopen()函数打开文件。
句法:
fptr = fopen(“file_name”, “mode”);
例子:
fopen(“D:\\geeksforgeeks\\newprogramgfg.txt”, “w”);
fopen(“D:\\geeksforgeeks\\oldprogramgfg.bin”, “rb”);
- 假设文件 newprogramgfg.txt 不存在于位置 D:\geeksforgeeks。第一个函数创建一个名为 newprogramgfg.txt 的新文件,并按照模式“w”打开它以进行写入。写入模式允许您创建和编辑(覆盖)文件的内容。
- 假设第二个二进制文件 oldprogramgfg.bin 存在于位置 D:\geeksforgeeks。第二个函数打开现有文件以二进制模式“rb”读取。读取模式只允许一个人读取文件,一个人不能写入文件。
C中的文件打开模式:Mode Meaning of Mode During Inexistence of file r Open for reading. If the file does not exist, fopen( ) returns NULL. rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL. w Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. wb Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a Open for append. Data is added to the end of the file. If the file does not exist, it will be created. ab Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created. r+ Open for both reading and writing. If the file does not exist, fopen( ) returns NULL. rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL. w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. wb+ Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a+ Open for both reading and appending. If the file does not exist, it will be created. ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
关闭文件
该文件应在读取或写入后关闭。使用 fclose()函数关闭文件。
句法:
fclose(fptr);
这里,fptr 是与要关闭的文件关联的文件类型指针。
读取和写入文本文件
为了读取和写入文本文件,使用函数 fprintf() 和 fscanf()。它们是 printf() 和 scanf() 函数的文件版本。唯一的区别是 fprintf() 和 fscanf() 需要指向结构文件的指针。
写入文本文件:
句法:
FILE *filePointer;
filePointer = fopen(“filename.txt”, “w”)
下面是写入文本文件的 C 程序。
C
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
// Get the data to be written in file
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer"
+ " Science Portal for Geeks";
// Open the existing file GfgTest.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("GfgTest.txt", "w");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Write the dataToBeWritten into the file
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fputs()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully written"
+ " in file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}
C
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r" attribute
filePointer = fopen("GfgTest.txt", "r");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully read"
+ " from file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"wb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin is"
+ " written successfully");
fclose(fptr);
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"rb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum),
1, fptr);
printf("n1: %d\tn2: %d\tn3: %d",
num.n1, num.n2, num.n3);
printf("\n");
}
fclose(fptr);
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
// Get the data to be appended in file
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics";
// Open the existing file GfgTest.txt using
// fopen() in append mode using "a" attribute
filePointer = fopen("GfgTest.txt", "a");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Append the dataToBeWritten into the file
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fputs()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully appended"
+ " in file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
// Opening the file in
// append mode
if ((fptr = fopen("C:\\GfgTest.bin",
"ab"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 10; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin"
+ " is appended successfully");
fclose(fptr);
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics.";
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r+" attribute
filePointer = fopen("GfgTest.txt", "r+");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
printf(
"\nData successfully read"
+ " from file GfgTest.txt");
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fprintf()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
printf("\nData successfully"
+ " written to the file");
// Closing the file using fclose()
fclose(filePointer);
printf("\nThe file is now closed.");
}
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"rb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum),
1, fptr);
printf("n1: %d\tn2: %d\tn3: %d",
num.n1, num.n2, num.n3);
printf("\n");
}
printf("Data successfully read from the file");
for (n = 1; n < 7; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin"
+ " is written successfully");
fclose(fptr);
return 0;
}
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
char dataToBeWritten[100]
= "It is a platform"
+ " for learning language"
+ " tech related topics.";
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r+" attribute
filePointer = fopen("GfgTest.txt", "w+");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fprintf()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
printf("Data successfully"
+ " written to the file\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
printf("\nData successfully read"
+ " from file GfgTest.txt");
// Closing the file using fclose()
fclose(filePointer);
printf("\nThe file is now closed.");
}
return 0;
}
输出:
从文件中读取:
句法:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
下面是读取文本文件的 C 程序。
C
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r" attribute
filePointer = fopen("GfgTest.txt", "r");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully read"
+ " from file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}
输出:
在二进制文件中读取和写入
写一个二进制文件:
句法:
FILE *filePointer;
filePointer = fopen(“fileName.bin”, “wb”);
要将数据写入二进制文件,需要 fwrite()函数。这个函数有四个参数:
- 要写入磁盘的数据的地址。
- 要写入磁盘的数据大小。
- 此类数据的数量。
- 指向要写入的文件的指针。
句法:
fwrite(addressData, sizeofData, numbersData, pointerToFile);
下面是实现上述方法的 C 程序:
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"wb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin is"
+ " written successfully");
fclose(fptr);
return 0;
}
从二进制文件中读取:
句法:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “rb”);
要从二进制文件中读取数据,使用 fread(0函数。与 fwrite()函数类似,该函数也有四个参数。
句法:
fread(addressData, sizeofData, numbersData, pointerToFile);
下面是实现上述方法的 C 程序:
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"rb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum),
1, fptr);
printf("n1: %d\tn2: %d\tn3: %d",
num.n1, num.n2, num.n3);
printf("\n");
}
fclose(fptr);
return 0;
}
输出:
在文本文件中追加内容
句法:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “a”);
以追加模式打开文件后,其余任务与在文本文件中写入内容相同。
以下是将字符串附加到文件的示例:
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
// Get the data to be appended in file
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics";
// Open the existing file GfgTest.txt using
// fopen() in append mode using "a" attribute
filePointer = fopen("GfgTest.txt", "a");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Append the dataToBeWritten into the file
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fputs()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully appended"
+ " in file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}
输出:
在二进制文件中追加内容
句法:
FILE * filePointer;
filePointer = fopen(“fileName.bin”, “ab”);
以追加模式打开文件后,其余任务与将内容写入二进制文件相同。
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
// Opening the file in
// append mode
if ((fptr = fopen("C:\\GfgTest.bin",
"ab"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 10; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin"
+ " is appended successfully");
fclose(fptr);
return 0;
}
输出:
打开文件以进行读取和写入
句法:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r+”);
文件以“r+'”模式打开,文件以读写模式打开。
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics.";
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r+" attribute
filePointer = fopen("GfgTest.txt", "r+");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
printf(
"\nData successfully read"
+ " from file GfgTest.txt");
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fprintf()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
printf("\nData successfully"
+ " written to the file");
// Closing the file using fclose()
fclose(filePointer);
printf("\nThe file is now closed.");
}
return 0;
}
输出:
以二进制模式打开文件以进行读写
句法:
FILE * filePointer;
filePointer = fopen(“fileName.bin”, “rb+”);
C++
// C program to implement
// the above approach
#include
#include
struct threeNum {
int n1, n2, n3;
};
// Driver code
int main()
{
int n;
struct threeNum num;
// Declaring the file pointer
FILE* fptr;
if ((fptr = fopen("C:\\GfgTest.bin",
"rb"))
== NULL) {
printf("Error! opening file");
// Program exits if the file pointer
// returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum),
1, fptr);
printf("n1: %d\tn2: %d\tn3: %d",
num.n1, num.n2, num.n3);
printf("\n");
}
printf("Data successfully read from the file");
for (n = 1; n < 7; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite(&num, sizeof(struct threeNum),
1, fptr);
}
printf("The file GfgTest.bin"
+ " is written successfully");
fclose(fptr);
return 0;
}
输出:
以文本模式打开文件以进行读写
在此模式下,文件以文本模式打开并进行读写。如果文件存在,则文件中的内容被覆盖,如果文件不存在,则在这种情况下,创建一个新文件。
句法:
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “w+”);
C++
// C program to implement
// the above approach
#include
#include
// Driver code
int main()
{
// Declare the file pointer
FILE* filePointer;
char dataToBeWritten[100]
= "It is a platform"
+ " for learning language"
+ " tech related topics.";
// Declare the variable for the data
// to be read from file
char dataToBeRead[50];
// Open the existing file GfgTest.txt
// using fopen() in read mode using
// "r+" attribute
filePointer = fopen("GfgTest.txt", "w+");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fprintf()
fprintf(filePointer, dataToBeWritten);
fprintf(filePointer, "\n");
}
printf("Data successfully"
+ " written to the file\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50,
filePointer)
!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
printf("\nData successfully read"
+ " from file GfgTest.txt");
// Closing the file using fclose()
fclose(filePointer);
printf("\nThe file is now closed.");
}
return 0;
}