我正在学习介绍文件的教程(如何从文件读取和写入文件)
首先,这不是作业,这只是我寻求的一般帮助。
我知道如何一次读取一个单词,但我不知道如何一次读取一行,或者如何读取整个文本文件。
如果我的文件包含 1000 个单词怎么办?逐字读取整个文件是不切实际的。
我的名为“Read”的文本文件包含以下内容:
I love to play games
I love reading
I have 2 books
这是我迄今为止所取得的成就:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
有没有可能的方法来一次读取整个文件,而不是单独读取每一行或每个单词?
您可以使用
std::getline
:
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
另请注意,最好只使用构造函数中的文件名构造文件流,而不是显式打开(关闭也是如此,只需让析构函数完成工作)。
有关
std::string::getline()
的更多文档可以在 CPP Reference 中阅读。
读取整个文本文件的最简单方法可能就是连接这些检索到的行。
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');
}
我知道这是一个非常非常古老的线程,但我还想指出另一种方法,它实际上非常简单......这是一些示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
上面的解决方案都很棒,但是还有更好的解决方案“一次读取一个文件”:
ifstream ifs(filename);
ostringstream oss;
oss << ifs.rdbuf();
string entireFile = oss.str();
我认为你可以使用 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;
}
你好兄弟,这是一种使用此代码读取确切行中的字符串的方法
希望这可以帮助你!
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
祝你好运!
还有一个没有提到的方法是
std::vector
。
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
然后您可以简单地迭代向量并修改/提取您需要的内容/
您还可以使用它来一一读取文件中的所有行,然后打印 i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
希望这可以帮助你:)
下面的代码片段将帮助您读取由 unicode 字符组成的文件
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
读完后一定要关闭文件指针,否则会导致错误