刚开始学习C++,保存以便查找。
总体代码:
#include <unistd.h> //对系统API操作
#include <iostream> //IO数据流
#include <fstream> //文件读写
using namespace std;
//C++ txt文件读写
int main()
{
char *path = get_current_dir_name(); //调用系统API获取当前路径
string currentPath = path;
free(path); //释放指针
path = NULL; //指针重新赋值
int indexParent = currentPath.find_last_of("/");
string parentPath = currentPath.substr(0, indexParent);
string targetFile = parentPath + "/resource/test1.txt"; // 操作文件路径
cout << "currentPath:" << currentPath << endl;
cout << "parentPath:" << parentPath << endl;
cout << "targetFile:" << targetFile << endl;
ifstream readStream;
readStream.open(targetFile, ios::in); //文件路径 输入至内存
if (readStream.is_open())
{
string readStr;
indexParent = 0;
while (readStream >> readStr)
{
//以空格为单位输出
indexParent++;
cout << indexParent << " : " << readStr << endl;
}
readStream.close();
//添加内容
ofstream writeFile;
writeFile.open(targetFile, ios::out | ios::app); //文件路径 从内存输出|追加内容
writeFile << "\n名称五,地址五,类型五"; //换行符 内容
writeFile.close();
}
else
{
cout << "Open Error!" << endl;
}
fstream stream;
stream.open(targetFile, ios::in);
if (stream.is_open())
{
string readStr;
indexParent = 0;
while (stream >> readStr)
{
indexParent++;
cout << indexParent << " : " << readStr << endl;
}
stream.close();
stream.open(targetFile, ios::out | ios::app);
stream << "\n名称五,地址五,类型五";
stream.close();
}
else
{
cout << "Open Error!" << endl;
}
}
添加头文件
#include <unistd.h> //对系统API操作
#include <iostream> //IO数据流
#include <fstream> //文件读写
第一种方法,读写分开。
ifstream readStream;
readStream.open(targetFile, ios::in); //文件路径 输入至内存
if (readStream.is_open())
{
string readStr;
indexParent = 0;
while (readStream >> readStr)
{
//以空格为单位输出
indexParent++;
cout << indexParent << " : " << readStr << endl;
}
readStream.close();
//添加内容
ofstream writeFile;
writeFile.open(targetFile, ios::out | ios::app); //文件路径 从内存输出|追加内容
writeFile << "\n名称五,地址五,类型五"; //换行符 内容
writeFile.close();
}
else
{
cout << "Open Error!" << endl;
}
第二种方法,读写一体。
fstream stream;
stream.open(targetFile, ios::in);
if (stream.is_open())
{
string readStr;
indexParent = 0;
while (stream >> readStr)
{
indexParent++;
cout << indexParent << " : " << readStr << endl;
}
stream.close();
stream.open(targetFile, ios::out | ios::app);
stream << "\n名称五,地址五,类型五";
stream.close();
}
else
{
cout << "Open Error!" << endl;
}
编译:g++ 脚本名称.cc
运行:./a.out