C++ 使用 fstream 读取每个字符,包括空格和换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/116951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using fstream to read every character including spaces and newline
提问by Jason Etheridge
I wanted to use fstream
to read a txt file.
我想用来fstream
读取一个txt文件。
I am using inFile >> characterToConvert
, but the problem is that this omits any spaces and newline.
我正在使用inFile >> characterToConvert
,但问题是这省略了任何空格和换行符。
I am writing an encryption program so I need to include the spaces and newlines.
我正在编写一个加密程序,所以我需要包含空格和换行符。
What would be the proper way to go about accomplishing this?
实现这一目标的正确方法是什么?
回答by Jason Etheridge
Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's rdbuf()
method:
可能最好的方法是将整个文件的内容读入一个字符串,这可以使用 ifstream 的rdbuf()
方法轻松完成:
std::ifstream in("myfile");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
You can then use regular string manipulation now that you've got everything from the file.
既然您已经从文件中获得了所有内容,那么您就可以使用常规的字符串操作了。
While Tomekwas asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream.
当Tomek询问读取文本文件时,同样的方法也适用于读取二进制数据,尽管在创建输入文件流时需要提供 std::ios::binary 标志。
回答by luke
For encryption, you're better off opening your file in binary mode. Use something like this to put the bytes of a file into a vector:
对于加密,最好以二进制模式打开文件。使用类似这样的方法将文件的字节放入向量中:
std::ifstream ifs("foobar.txt", std::ios::binary);
ifs.seekg(0, std::ios::end);
std::ifstream::pos_type filesize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::vector<char> bytes(filesize);
ifs.read(&bytes[0], filesize);
Edit: fixed a subtle bug as per the comments.
编辑:根据评论修复了一个微妙的错误。
回答by Adam Holmberg
I haven't tested this, but I believe you need to clear the "skip whitespace" flag:
我还没有测试过这个,但我相信你需要清除“跳过空白”标志:
inFile.unsetf(ios_base::skipws);
I use the following reference for C++ streams: IOstream Library
我对 C++ 流使用以下参考: IOstream Library
回答by Iakov Minochkin
std::ifstream ifs( "filename.txt" );
std::string str( ( std::istreambuf_iterator<char>( ifs ) ),
std::istreambuf_iterator<char>()
);
回答by mmattax
The following c++ code will read an entire file...
以下 C++ 代码将读取整个文件...
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
ifstream myfile ("foo.txt");
if (myfile.is_open()){
while (!myfile.eof()){
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
return 0;
}
post your code and I can give you more specific help to your problem...
发布您的代码,我可以为您的问题提供更具体的帮助...
回答by CB Bailey
A lot of the benefit of the istream layer is providing basic formatting and parsing for simple types ro and from a stream. For the purposes that you describe, none of this is really important and you are just interested in the file as a stream of bytes.
istream 层的很多好处是为简单类型 ro 和来自流提供基本的格式化和解析。就您描述的目的而言,这些都不是很重要,您只是对作为字节流的文件感兴趣。
For these purpose you may be better of just using the basic_streambuf interface provided by a filebuf. The 'skip whitespace' behaviour is part of the istream interface functionality that you just don't need.
出于这些目的,您最好只使用 filebuf 提供的 basic_streambuf 接口。“跳过空白”行为是您不需要的 istream 接口功能的一部分。
filebuf underlies an ifstream, but it is perfectly valid to use it directly.
filebuf 是 ifstream 的基础,但直接使用它是完全有效的。
std::filebuf myfile;
myfile.open( "myfile.dat", std::ios_base::in | std::ios_base::binary );
// gets next char, then moves 'get' pointer to next char in the file
int ch = myfile.sbumpc();
// get (up to) the next n chars from the stream
std::streamsize getcount = myfile.sgetn( char_array, n );
Also have a look at the functions snextc (moves the 'get' pointer forward and then returns the current char), sgetc (gets the current char but doesn't move the 'get' pointer) and sungetc (backs up the 'get' pointer by one position if possible).
还要看一下函数 snextc(向前移动“get”指针,然后返回当前字符)、sgetc(获取当前字符但不移动“get”指针)和 sungetc(备份“get”指针)如果可能,指针指向一个位置)。
When you don't need any of the insertion and extraction operators provided by an istream class and just need a basic byte interface, often the streambuf interface (filebuf, stringbuf) is more appropriate than an istream interface (ifstream, istringstream).
当您不需要 istream 类提供的任何插入和提取运算符而只需要一个基本的字节接口时,通常 streambuf 接口(filebuf、stringbuf)比 istream 接口(ifstream、istringstream)更合适。
回答by jdmichal
You can call int fstream::get()
, which will read a single character from the stream. You can also use istream& fstream::read(char*, streamsize)
, which does the same operation as get()
, just over multiple characters. The given links include examples of using each method.
您可以调用int fstream::get()
,它将从流中读取单个字符。您还可以使用istream& fstream::read(char*, streamsize)
,它执行与 相同的操作get()
,只是在多个字符上。给定的链接包括使用每种方法的示例。
I also recommend reading and writing in binary mode. This allows ASCII control characters to be properly read from and written to files. Otherwise, an encrypt/decrypt operation pair might result in non-identical files. To do this, you open the filestream with the ios::binary
flag. With a binary file, you want to use the read()
method.
我还建议以二进制模式进行读写。这允许从文件中正确读取和写入 ASCII 控制字符。否则,加密/解密操作对可能会导致不同的文件。为此,您打开带有ios::binary
标志的文件流。对于二进制文件,您要使用该read()
方法。
回答by user1621518
Another better way is to use istreambuf_iterator, and the sample code is as below:
另一种更好的方法是使用istreambuf_iterator,示例代码如下:
ifstream inputFile("test.data");
string fileData(istreambuf_iterator<char>(inputFile), istreambuf_iterator<char>());
回答by user1621518
For encryption, you should probably use read(). Encryption algorithms usually deal with fixed-size blocks. Oh, and to open in binary mode (no translation frmo \n\r to \n), pass ios_base::binary as the second parameter to constructor or open() call.
对于加密,您可能应该使用read()。加密算法通常处理固定大小的块。哦,要以二进制模式打开(没有从 frmo \n\r 转换为 \n),请将 ios_base::binary 作为第二个参数传递给构造函数或 open() 调用。
回答by Flame
Simple
简单的
#include <fstream>
#include <iomanip>
ifstream ifs ("file");
ifs >> noskipws
that's all.
就这样。