1、File*
(1) 写入txt
void WriteTXT()
{
std::string filepath;
FILE* file = fopen(filepath.c_str(), "wt+");
if (file)
{
std::string str = "test";
std::stringstream ss;
ss << "write txt " << str;
fputs(ss.str().c_str(), file);
fclose(file);
}
}
(2) 按行读取txt
void ReadTXT()
{
std::string filePath;
FILE* file = fopen(filePath.c_str(), "r");
if (file)
{
char buff[1000];
while(fgets(buff, 1000 ,file) != NULL)
{
char *pstr = strtok(buff, "\n");
if (pstr)
{
std::string str = pstr;
}
}
fclose(file);
}
}
2、ifstream、ofstream
(1) 文件打开方式
ios::in | 读文件打开 |
ios::out | 写文件打开 |
ios::ate | 从文件尾打开 |
ios::app | 追加方式打开 |
ios::binary | 二进制方式打开 |
ios::trunc | 打开一个文件时,清空其内容 |
ios::nocrate | 打开一个文件时,如果文件不存在,不创建 |
ios::noreplace | 打开一个文件时,如果文件不存在,创建该文件 |
(2) 写入txt
#include <fstream>
void WriteTXT()
{
ofstream ofs;
ofs.open("text.txt", ios::out);
ofs << "write message" << endl;
ofs.close();
}
(3) 读取txt
#include <fstream>
void ReadTXT()
{
ifstream ifs;
ifs.open("text.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败!" << endl;
return;
}
// 方式一
char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}
// 方式二
char buf[1024];
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
}
// 方式三
string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
}
// 方式四,不推荐用
char c;
while ((c=ifs.get()) != EOF) {
cout << c;
}
ifs.close();
}
原文链接: https://www.cnblogs.com/zerotoinfinity/p/12626389.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/195267
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!