c++ 文件操作

这个博客介绍了使用C++进行文件操作的几种方式,包括新建文件并写入数据、清空文件后写入新内容以及追加内容到文件。通过示例代码展示了如何使用`ofstream`和`ifstream`打开、写入和读取文本文件。最后,还演示了如何从用户输入接收文件名并进行追加操作。
摘要由CSDN通过智能技术生成
// open a new file
#include <iostream>
#include <fstream>

int main()
{
  std::ofstream file;
  file.open("hello.txt"); // open an new file
  file << "hey"; // write into file
  file.close();
  return 0;
}

// file write replace all content
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
  std::ofstream file ("hello.txt"); // open an empty file
  
  std::vector<std::string> names; // string vector
  names.push_back("Jim");
  names.push_back("Lily");
  names.push_back("Lucy");

  for(std::string name: names) // for name in names
  {
    file << name << std::endl;
  }

  file.close();
  return 0;
}

// append in the file
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
  std::ofstream file ("hello.txt", std::ios::app); // append in the file
  
  std::vector<std::string> names; // string vector
  names.push_back("Jim");
  names.push_back("Lily");
  names.push_back("Lucy");

  for(std::string name: names) // for name in names
  {
    file << name << std::endl;
  }

  file.close();
  return 0;
}

// input file name and open it
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
  std::string filename;
  std::cin >> filename; // input the filename
  std::ofstream file (filename.c_str(), std::ios::app); // append in the file

  if(file.is_open()) // check if it is open
  {
    std::cout << "success\n";
  }
  
  std::vector<std::string> names; // string vector
  names.push_back("Jim");
  names.push_back("Lily");
  names.push_back("Lucy");

  for(std::string name: names) // for name in names
  {
    file << name << std::endl;
  }

  file.close();
  return 0;
}

// read file
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
  std::ifstream file ("hello.txt"); // ifstream to read

  std::vector<std::string> names; // define a vector

  std::string input; // define a string
  while(file >> input) // if there is string in file
  {
    names.push_back(input); // put string into vector
  }

  for(std::string name : names)
  {
    std::cout << name << std::endl;
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值