21xrx.com
2024-09-20 00:51:53 Friday
登录
文章检索 我的文章 写文章
C++ 文件读写操作
2023-07-05 09:28:18 深夜i     --     --
C++ 文件 操作

C++ 是一种高效且功能丰富的编程语言,可以用于各种任务,其中包括对文件进行读写操作。文件读写是许多程序的核心要素,因为程序常需要从文件中读取数据或将结果写入文件。

C++ 提供了多种文件读写操作的方式。以下是几种常见的 C++ 文件读写操作方式:

1. 使用 ifstream 和 ofstream 类进行文件读写操作

C++ 标准库中的 ifstream 和 ofstream 类分别用于文件输入和输出。可以使用这两个类打开文件,读写文件数据并关闭文件。以下是一个示例代码:


#include <fstream>

#include <iostream>

#include <string>

int main() {

 std::string filename = "example.txt";

 std::ofstream fileout(filename.c_str());

 if (fileout.is_open()) {

  fileout << "Hello, world!\n";

  fileout.close();

 }

 std::ifstream filein(filename.c_str());

 if (filein.is_open()) {

  std::string line;

  while (std::getline(filein, line))

   std::cout << line << std:endl;

  

  filein.close();

 }

 return 0;

}

2. 使用 fstream 类进行文件读写操作

C++ 标准库中的 fstream 类可用于同时读写文件。fstream 和 ifstream 和 ofstream 类的用法类似,下面是一个类似的示例代码:


#include <fstream>

#include <iostream>

#include <string>

int main() {

 std::string filename = "example.txt";

 std::fstream fileio(filename.c_str(), std::ios::in | std::ios::out | std::ios::trunc);

 if (fileio.is_open()) {

  fileio << "Hello, world!\n";

  fileio.seekg(0, fileio.beg); // 将文件指针移动到文件开头

  std::string line;

  while (std::getline(fileio, line))

   std::cout << line << std:endl;

  

  fileio.close();

 }

 return 0;

}

3. 使用 fscanf 和 fprintf 函数进行文件读写操作

除了使用 C++ 标准库中的类,也可以使用 C 标准库中的 fscanf 和 fprintf 函数进行文件读写操作。这需要包含 stdio.h 头文件。以下是一个示例代码:


#include <stdio.h>

int main() {

 const char* filename = "example.txt";

 FILE* file = fopen(filename, "w");

 if (file != NULL) {

  fprintf(file, "Hello, world!\n");

  fclose(file);

 }

 file = fopen(filename, "r");

 if (file != NULL) {

  char line[1024];

  while (fgets(line, sizeof(line), file)) {

   printf("%s", line);

  }

  fclose(file);

 }

 return 0;

}

无论使用哪种方法进行文件读写,都需要确保在完成读写操作后关闭文件。如果不关闭文件,可能会出现未定义的行为,例如操作系统无法删除文件或进程卡死等问题。

综上所述,C++ 提供了多种灵活和高效的文件读写操作方式。使用正确的方式可以使代码更加清晰和可维护,同时还可以提高程序的性能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复