使用std–fstream处理文件「建议收藏」

使用std–fstream处理文件「建议收藏」fstream 文件操作总结 文件的操作一直在用 在此总结一下 fstream 的使用 std fstream 从 std ofstream 继承写入文件的功能 从 std ifstream 继承读取文件的功能 包含头文件 include 使用 open 和 close 打开和关闭文件 include include using namespace std int

fstream文件操作总结

文件的操作一直在用,在此总结一下:fstream的使用

std::fstream从std::ofstream继承写入文件的功能,从std::ifstream继承读取文件的功能.

包含头文件
 #include 

----

使用open( )和close( )打开和关闭文件

#include
#include
using namespace std;
int main()
{
fstream myFile;
//如果不存在即创建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);

if (myFile.is_open())
cout << "open is ok " << endl;
myFile.close();
system("pause");
}

输出结果:

open( )函数:第一个参数是要打开的文件的路径和名称(或指定当前路径),第二参数是文件的打开模式。
具体属性可参考网址

其他文件读取方式:

//使用构造函数打开
fstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out | ios_base::trunc);
// 只想打开文件写入
ofstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out);
// 只想打开文件读取
ifstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::in);

2.使用open( )创建及写入文本,使用运算符<<

#include
#include
using namespace std;
int main()
{
fstream myFile;
//如果不存在即创建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);
if (myFile.is_open())
cout << "open is ok " << endl;
// 写入文本
myFile << "hello fstream" << endl;
cout << "Finished" << endl;
myFile.close();
system("pause");
}

3.使用open( )创建及读入文本,使用运算符>>

#include
#include
#include
using namespace std;
int main()
{
fstream myFile;
//如果不存在即创建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::in);
if (myFile.is_open())
cout << "open is ok " << endl;

string fileTxt;
while (myFile.good())
{
getline(myFile,fileTxt);
cout << fileTxt << endl;

}
cout << "Finished" << endl;
myFile.close();
system("pause");
}

txt文件内容


输出

编程小号
上一篇 2025-03-20 21:57
下一篇 2025-02-14 23:40

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/126789.html