#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
std::vector<std::string> ReadLines(std::string& filename)
{
std::ifstream file(filename);
string str;
std::vector<std::string> lines;
while (getline(file, str)) {
lines.push_back(str);
}
return lines;
}
std::string ReadFile(std::string& filename)
{
std::ifstream file;
//以只读方式打开文件
file.open(filename, std::ios::in);
//指针定位到文件末尾
file.seekg(0, std::ios::end);
int fileLength = file.tellg();
//指定定位到文件开始
file.seekg(0, std::ios::beg);
char* buffer = new char[fileLength + 1];
file.read(buffer, fileLength);
buffer[fileLength] = '\0';
std::string content = buffer;
if (buffer) {
delete[] buffer;
}
file.close();
return content;
}
void WriteFile(std::string content, std::string savefile)
{
std::ofstream out(savefile);
if (out.is_open())
{
out << content;
out.close();
}
}
int main()
{
std::string file = "result.txt";
WriteFile("123", file);
std::string res = ReadFile(file);
std::cout << res << "\n";
std::vector<std::string> lines = ReadLines(file);
std::cout << lines.size() << "\n";
getchar();
return 0;
}
[C++][windows][原创]文件读写逐行读文件
于 2023-06-25 10:53:58 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)