首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++IO流读取文件的时候的一个有关问题

2012-03-22 
C++IO流读取文件的时候的一个问题!C/C++ codestring s1string s2jj072513zofstream off(pdata.dat,

C++IO流读取文件的时候的一个问题!

C/C++ code
           string s1;       string s2="jj072513z";        ofstream off("pdata.dat",ios_base::binary);    off.write((char *)&s2,sizeof(s2));    off.close();    ifstream iff("pdata.dat",ios_base::binary);    iff.read((char *)&s1,sizeof(s1));    iff.close();    cout<<s1;

这么写没问题,
C/C++ code
        string s1;    string s2="jj072513z";        ifstream iff("pdata.dat",ios_base::binary);    iff.read((char *)&s1,sizeof(s1));    iff.close();    cout<<s1;

这样也能读出来
C/C++ code
         string s1;     ifstream iff("pdata.dat",ios_base::binary);    iff.read((char *)&s1,sizeof(s1));    iff.close();    cout<<s1;

但是这样就内存出错!

[解决办法]
istream& read ( char* s, streamsize n );



Read block of data

Reads a block of data of n characters and stores it in the array pointed by s.

If the End-of-File is reached before n characters have been read, the array will contain all the elements read until it, and the failbit and eofbit will be set (which can be checked with members fail and eof respectively).

Notice that this is an unformatted input function and what is extracted is not stored as a c-string format, therefore no ending null-character is appended at the end of the character sequence.

Calling member gcount after this function the total number of characters read can be obtained.

Parameters

s
Pointer to an allocated block of memory where the content read will be stored.
n
Integer value of type streamsize representing the size in characters of the block of data to be read.

Return Value
The functions return *this.

Errors are signaled by modifying the internal state flags:


 string s1; //这个的空间其实还没有分配,上面的能够得到结果都是侥幸的

[解决办法]
兄弟,string的实现可以打开<string>这个头文件看看。
[解决办法]
1楼的不对吧,string是一个类,string s1;应该是调用默认构造函数构造,分配空间

楼主使用sizeof(s2)不对,因为string是类,其大小在VC中是16字节

你的三个程序都有缺陷,后面读出来是因为你的第一个程序运行后pdata文件已经保存了
你可以删除文件再运行后面2个文件就知道了

string作为类,里面的内容大概是一个字符串指针,几个int值, 你的write方法不适应它。
应该用char* s = "jj072513z";
[解决办法]
不进行初始化...string刚开始的容量为0...
[解决办法]
wstring s1;
wstring s2= L"jj072513z";
wofstream of(L"pdata.dat", ios_base::binary);
of << s2;
of.close();
wifstream iff(L"pdata.dat", ios_base::binary);
iff >> s1;
iff.close();
wcout << s1 << endl;
getchar();
[解决办法]
string s2="jj072513z";
off.write((char *)&s2,sizeof(s2)); // 这样是不能将"jj072513z"写到文件中去的,解释如三楼所说

应该这样做:
off.write(s2.c_str(), s2.length());

c_str()和length()是string提供的方法,
c_str()返回string对象中的字符串的首地址,
length()返回string对象中字符的个数。

热点排行