C++ C++;如果流读得太多?
我正在尝试读取一个文件并输出内容。一切正常,我可以看到内容,但它似乎增加了约14个空字节的结尾。有人知道这个代码有什么问题吗C++ C++;如果流读得太多?,c++,html,file,char,ifstream,C++,Html,File,Char,Ifstream,我正在尝试读取一个文件并输出内容。一切正常,我可以看到内容,但它似乎增加了约14个空字节的结尾。有人知道这个代码有什么问题吗 int length; char * html; ifstream is; is.open ("index.html"); is.seekg (0, ios::end);
int length;
char * html;
ifstream is;
is.open ("index.html");
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
html = new char [length];
is.read(html, length);
is.close();
cout << html;
delete[] html;
int长度;
char*html;
如果流是;
is.open(“index.html”);
is.seekg(0,ios::end);
长度=is.tellg();
is.seekg(0,ios::beg);
html=新字符[长度];
is.read(html,长度);
is.close();
cout您没有在char数组上放置空终止符。这并不是说流读取太多,因为在没有空终止符的情况下,cout不知道何时停止打印
如果要读取整个文件,这会更容易:
std::ostringstream oss;
ifstream fin("index.html");
oss << fin.rdbuf();
std::string html = oss.str();
std::cout << html;
std::ostringstream oss;
ifstreamfin(“index.html”);
oss这是因为html
不是以null结尾的字符串,std::cout
一直打印字符,直到找到\0
,否则可能会使程序崩溃
这样做:
html = new char [length +1 ];
is.read(html, length);
html[length] = '\0'; // put null at the end
is.close();
cout << html;
cout.write
将在length
字符数之后立即停止打印。+1。IIRC seek技巧在告诉您文件大小方面甚至都不那么可靠,特别是当您以文本模式打开文件时。
cout.write(html, length);