Mod*_*ody 78 c++ fstream iostream file-handling
我在一个介绍文件的教程中(如何从\到文件读取和写入)
首先,这不是一个功课,这只是我正在寻求的一般帮助.
我知道如何一次读一个单词,但我不知道如何一次读一行或如何读取整个文本文件.
如果我的文件包含1000个单词怎么办?阅读每个单词是不切实际的.
我的名为(Read)的文本文件包含以下内容:
我喜欢玩我喜欢阅读的游戏我有2本书
这是我迄今为止所取得的成就:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Run Code Online (Sandbox Code Playgroud)
有没有办法一次读取整个文件,而不是分别读取每一行或每个单词?
111*_*111 148
你可以使用std::getline:
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,最好只使用文件名构造文件流,而不是显式打开文件流(同样适用于关闭,只需让析构函数完成工作).
有关详细信息,请std::string::getline()参阅CPP参考.
读取整个文本文件的最简单方法可能就是连接那些检索到的行.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
Run Code Online (Sandbox Code Playgroud)
use*_*553 19
我知道这是一个非常老的线程,但我还想指出另一种实际上非常简单的方法......这是一些示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
上面的解决方案都很棒,但是还有一个更好的解决方案“一次读取一个文件”:
ifstream ifs(filename);
ostringstream oss;
oss << ifs.rdbuf();
string entireFile = oss.str();
Run Code Online (Sandbox Code Playgroud)
我认为你可以使用 istream .read() 函数。您可以使用合理的块大小循环并直接读取到内存缓冲区,然后将其附加到某种任意内存容器(例如 std::vector)。我可以写一个例子,但我怀疑你想要一个完整的解决方案;如果您需要任何其他信息,请告诉我。
好吧,要做到这一点,也可以使用 C++ 中提供的 freopen 函数 - http://www.cplusplus.com/reference/cstdio/freopen/并按如下方式逐行读取文件 -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)