读书人

c++输出流有关问题

发布时间: 2013-01-08 14:02:14 作者: rapoo

c++输出流问题
本帖最后由 xhwjc2008 于 2012-12-17 17:05:17 编辑 我最后的p输出不到控制台窗口中,或者是没在控制台窗口中显示


#include <fstream>
#include <iostream>
#include <stdlib.h>

using namespace std;

void main()
{ //write text file
ofstream outFileObj;
outFileObj.open("E:\\text.txt",ios::out);
if(!outFileObj)
{
cerr<<"Create file faile";
exit(-1);
}
outFileObj << "Hello!\n";
outFileObj.close();


//read text file by binary
char * p;
p = (char *)malloc(7);
ifstream inObj("E:\\text.txt",ios::in|ios::binary);
if(!inObj)
{
cout << "can not open file";
abort();
return;
}

inObj.read(p, 7);
cout << p << endl; //为什么输出不到窗口中? 程序是在vs2008上可执行的

free(p);
p = NULL;
}

[解决办法]
inObj.read(p, 7);

改为
inObj.read(p, 6);


[解决办法]
引用:
引用:
C/C++ code?1inObj.read(p, 7);
改为
C/C++ code?1inObj.read(p, 6);

那我的换行符是不是读不出来了。



p = (char *)malloc(1024); //多分配 一点,别不舍得内存


[解决办法]
引用:
引用:引用:
C/C++ code?1inObj.read(p, 7);
改为
C/C++ code?1inObj.read(p, 6);

那我的换行符是不是读不出来了。


p = (char *)malloc(1024); //多分配 一点,别不舍得内存


多分配内存输出会有乱码。没有明确的'\0’结尾。
[解决办法]

memset(p,0,7);//内存空间初始化下,不过最好不要用具体数字,
//只能读6个,因为最后一个必须是0,不然后cout不知道什么地方终止,直到遇见\0

读书人网 >C++

热点推荐