C++ 简单的txt文件读取
本人初学C++ 如有遗漏和错误,望斧正!
本文只是简单的介绍一下C++对txt文件的简单读和写
希望大家喜欢
给个赞就最好了
(。・∀・)ノ
1. C++ txt 文件 写
1.1演示
#include<iostream>
#include<fstream> // 读写专用文件
int main()
{
using namespace std;
ofstream outFile; // 建立一个名为outFile的对象
outFile.open("filename.txt"); //建立连接文件及所写文件
int a; // 建立int a
cin >> a; // 输入 a 的值
outFile << a << endl; // 输入出a的值到outFilew所连接的文件中
outFile.close(); // 关闭文件
system("pause");
return 0;
}
1.2注意事项
outFile.open("filename.txt"); // 如果open的是一个已存在的txt文件那么,open()就会截断文件及---丢失原有的内容
2.C++ txt 文件 读
2.1测试文档
测试文档名为“filename.txt”内容为
123
234
345
2.2演示
#include<iostream>
#include<fstream> // 读写专用库
#include<cstdlib> // exit() 函数 用于 跳出 程序
int main()
{
using namespace std;
ifstream inFile; // 建立名为inFile的对象
inFile.open("filename.txt");// 连接要读取数据的文档
if (!inFile.is_open()) // 检查 文档是否打开 否则跳出
{
cout << "Dead!" << endl;
exit(EXIT_FAILURE);
}
int Ret[10] = {0};
int count = 0;
///
while (inFile.good()) // 当文件 是 正差输出 并且没有 遇到 EOF 时
{
inFile >> Ret[count]; // 存入
count++;
}
有更优秀的写法↓
if (inFile.eof())
{
for(int i=0;i<count-1;i++)
{
cout << Ret[i] << endl; // 倒序输出
}
}
else if (inFile.fail())
cout << "INPUT mismatch" << endl; // 文件打开失败
else
cout << "dead for unknown reason" << endl; // 未知原因
if (count == 0)
{
cout << "without data" << endl;//没有读到数字
}
else
{
cout << "DONE!" << endl;//结束
}
inFile.close(); // 关闭文件
system("pause");
return 0;
}
2.3 精简 写法
while (inFile >> Ret[count])
{
count++;
//循环
}