// 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;
}
c++ 文件操作
最新推荐文章于 2024-07-19 16:30:03 发布
这个博客介绍了使用C++进行文件操作的几种方式,包括新建文件并写入数据、清空文件后写入新内容以及追加内容到文件。通过示例代码展示了如何使用`ofstream`和`ifstream`打开、写入和读取文本文件。最后,还演示了如何从用户输入接收文件名并进行追加操作。
摘要由CSDN通过智能技术生成