现在的位置: 首页 > 综合 > 正文

C++里如何读入整个文件

2012年10月05日 ⁄ 综合 ⁄ 共 588字 ⁄ 字号 评论关闭
在C++中,一般喜欢用输入输出流来进行文件操作。但在用fstream操作的时候,读到一个空格后,就会停止。有什么办法能完整地读入整个文件而不抛弃空格、换行符?即保留原有的格式……
有两种方法可以实现在C++里完整地读入整个文件。
第一种方法示例代码:
string str,strTotal; ifstream in; in.open(“myfile.txt”); getline(in,str); while ( in ) { strTotal += str; getline(in,str); }

第二种方法,用binary的方式读写整个文件 示例代码1:
std::ifstream file1(“in.txt”, ios::in | ios::binary); std::ofstream file2(“out.txt”, ios::out | ios::binary);
char input; while(file1.read(&input, 1)) { file2.write(&input, 1); }
file1.close(); file2.close();

示例代码2:
// reading a complete binary file #include <iostream> #include <fstream> using namespace std;
ifstream::pos_type size; char * memblock;
int main () { [...]

抱歉!评论已关闭.