将整个ASCII文件读入C ++ std :: string [重复]
本文翻译自:Read whole ASCII file into C++ std::string [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- What is the best way to read an entire file into a std::string in C++? 在C ++中将整个文件读入std :: string的最佳方法是什么? 11 answers 11个答案
I need to read a whole file into memory and place it in a C++ std::string
. 我需要将整个文件读入内存并将其放在C ++ std::string
。
If I were to read it into a char[]
, the answer would be very simple: 如果我将其读入char[]
,答案将非常简单:
std::ifstream t;
int length;
t.open("file.txt"); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle// ... Do stuff with buffer here ...
Now, I want to do the exact same thing, but using a std::string
instead of a char[]
. 现在,我想做完全相同的事情,但是使用std::string
而不是char[]
。 I want to avoid loops, ie I don't want to: 我想避免环路,即我不想 :
std::ifstream t;
t.open("file.txt");
std::string buffer;
std::string line;
while(t){
std::getline(t, line);
// ... Append line to buffer and go on
}
t.close()
Any ideas? 有任何想法吗?
#1楼
参考:https://stackoom.com/question/Autx/将整个ASCII文件读入C-std-string-重复
#2楼
I could do it like this: 我可以这样做:
void readfile(const std::string &filepath,std::string &buffer){std::ifstream fin(filepath.c_str());getline(fin, buffer, char(-1));fin.close();
}
If this is something to be frowned upon, please let me know why 如果您对此不满意,请告诉我为什么
#3楼
I think best way is to use string stream. 我认为最好的方法是使用字符串流。 simple and quick !!! 简单快捷!
#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
int main() {std::ifstream inFile;inFile.open("inFileName"); //open the input filestd::stringstream strStream;strStream << inFile.rdbuf(); //read the filestd::string str = strStream.str(); //str holds the content of the filestd::cout << str << "\n"; //you can do anything with the string!!!
}
#4楼
I figured out another way that works with most istreams, including std::cin! 我想出了适用于大多数istream的另一种方法,包括std :: cin!
std::string readFile()
{stringstream str;ifstream stream("Hello_World.txt");if(stream.is_open()){while(stream.peek() != EOF){str << (char) stream.get();}stream.close();return str.str();}
}
#5楼
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! 更新:事实证明,这种方法虽然很好地遵循了STL习惯用法,但实际上效率低得多! Don't do this with large files. 不要对大文件执行此操作。 (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html ) (请参阅: http : //insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html )
You can make a streambuf iterator out of the file and initialize the string with it: 您可以从文件中制作一个streambuf迭代器,并使用它初始化字符串:
#include <string>
#include <fstream>
#include <streambuf>std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());
Not sure where you're getting the t.open("file.txt", "r")
syntax from. 不知道从哪里获取t.open("file.txt", "r")
语法。 As far as I know that's not a method that std::ifstream
has. 据我所知,这不是std::ifstream
具有的方法。 It looks like you've confused it with C's fopen
. 您似乎已经将其与C的fopen
混淆了。
Edit: Also note the extra parentheses around the first argument to the string constructor. 编辑:还请注意字符串构造函数的第一个参数周围的多余括号。 These are essential . 这些是必不可少的 。 They prevent the problem known as the " most vexing parse ", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results. 它们可以防止称为“ 最烦人的解析 ”的问题,在这种情况下,它实际上不会像通常那样给您带来编译错误,但会给您带来有趣的(错误的)结果。
Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation): 遵循KeithB在评论中的观点,这是一种预先分配所有内存的方法(而不是依赖于字符串类的自动重新分配):
#include <string>
#include <fstream>
#include <streambuf>std::ifstream t("file.txt");
std::string str;t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);str.assign((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());
#6楼
I don't think you can do this without an explicit or implicit loop, without reading into a char array (or some other container) first and ten constructing the string. 我认为如果没有显式或隐式循环,而没有先读入char数组(或其他容器),又没有十个构造字符串的方法,您将无法做到这一点。 If you don't need the other capabilities of a string, it could be done with vector<char>
the same way you are currently using a char *
. 如果不需要字符串的其他功能,则可以使用vector<char>
来完成,就像您当前使用char *
。
将整个ASCII文件读入C ++ std :: string [重复]相关推荐
- Qt选择文件对话框-中文路径-转std::string
#include <QFileDialog> #pragma execution_character_set("utf-8") QString path = QFile ...
- 在java读字符串入文件_如何在java中将文件读入字符串?
我已经将文件读入String. 该文件包含各种名称,每行一个名称. 现在的问题是我想在String数组中使用这些名称. 为此我写了以下代码: String [] names = fileString. ...
- C++/C++11中std::string用法汇总
C++/C++11中std::string是个模板类,它是一个标准库.使用string类型必须首先包含<string>头文件.作为标准库的一部分,string定义在命名空间std中. st ...
- 如何将std :: string转换为const char *或char *?
如何将<code>std::string转换为char*或const char* ? #1楼 看看这个: string str1("stackoverflow"); c ...
- std::string用法总结
c++stdstring 在平常工作中经常用到了string类,本人记忆了不好用到了的时候经常要去查询.在网上摘抄一下总结一下,为以后的查询方便: string类的构造函数: string(const ...
- std::string 用法
string类的构造函数: string(const char *s); //用c字符串s初始化string(int n,char c); //用n个字符c初始化 string类的字符操作: cons ...
- 对ASCII文件的操作
ASCII文件又称文本(text)文件或字符文件,它的每一个字节放一个ASCII代码,代表一个字符 对ASCII文件的读写操作可以用以下两种方法: (1)用流插入运算符"<<&q ...
- c语言读取ascii文件,C++对ASCII文件的读写操作
如果文件的每一个字节中均以ASCII代码形式存放数据,即一个字节存放一个字符,这个文件就是ASCII文件(或称字符文件).程序可以从ASCII文件中读入若干个字符,也可以向它输出一些字符. 对ASCI ...
- C++ 对文件的最常用基操之对 ASCII 文件(文本文件、字符文件)的操作
C++ 对文件的最常用操作 ☆ 基本概念 根据文件中数据的组织方式,可以将文件分为 ASCII 文件 和 二进制文件. 前者又称为文本文件或字符文件,后者又称为内部格式文件或字节文件. 本文讲解针对 ...
最新文章
- Python网络爬虫--BeautifulSoup库的基本元素
- java不使用IDE导入json
- 一位数据科学家的私房工具清单
- 一文看懂NumPy的切片中常用的冒号
- 一种绕开反病毒引擎的方法
- 用 Hasor 谈一谈MVC设计模式
- [GO]append的扩容
- python运维处理序列_Python运维开发:02 序列
- 使用TensorFlow.js从网络摄像头进行实时AI情感检测
- Bootstrap学习之三:使用排版
- Linear Programming and network flows P17 笔记
- php ora01017,使用dblink出现ORA-01017
- 抽奖活动mysql表设计_抽奖项目的系统设计方案
- wps2019无法使用粘贴复制快捷键
- 【ARM 】CMSIS
- win7计算机用户名在哪改,win7系统怎么更改用户账户名称|win7修改用户名的方法...
- C#盛金公式求解一元三次方程
- android libbinder – Binder的Native实现
- 感知复合型人才的重要性!
- HCS12X微控制器的外部总线接口介绍