读书人

关于fstream的追加模式的有关问题(是

发布时间: 2012-03-21 13:33:14 作者: rapoo

关于fstream的追加模式的问题(是不是编译器版本的问题)
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main()
{ char ch;
fstream iofile("c://text.txt",ios_base::in|ios_base::app);
if(!iofile)
cerr<<"iofile不能打开"<<endl;
else
{
iofile.seekg(0);
while(iofile>>ch)
iofile<<ch+32<<endl;
}

}
//程序想法是把text中的大写字母变成小写加到文件后面
编译环境vc6.0,每次编译都通过,运行是每次都显示iofile无法打开,取消ios_base::in|ios_base::app后
程序没问题
请教大家为什么我的追加模式没有用

[解决办法]

1. "ios_base::in" means open file for input, "ios_base::app" means "append, or write only to the end of a file".

2. Read and Write position are not separately maintained, there is only one "STREAM POSITION" for each object. Thus, I don't think "ios_base::in || ios_base::app" will make any sense.

3. You could try using just "fstream iofile("c://text.txt");", since the standard assumes "ios::in | ios::out" as default mode. However, it is still not a good idea to do input and output with only one object. As I said, there is only one stream position, and you have to "seek" the correct position before write.

4. "ios_base::in" and "ios_base::out" are kind of old coding style, new compiler might not recognize them. Try "ios::in | ios::out" instead.

5. To summarize, I suggest you to use one object with mode "ios::in" for reading, and another object with mode "ios::app" for writing.

Cheers.
[解决办法]
#include <iostream >
#include <fstream >
#include <string >
using namespace std;
void main()
{ char ch;
fstream iofile("c://text.txt",ios_base::in |ios_base::out);
if(!iofile)
cerr <<"iofile不能打开" <<endl;
else
{
unsigned int fileEnd=iofile.size;//---------
//iofile.seekg(0); //-------------VV
for(int i=0;i<fileEnd;i++){
iofile.seekg(i);iofile>>ch;
if(ch<0x41||ch>0x51)continue; //或 iofile<<(ch<0x41||ch>0x51?ch:ch+32);大写转小写
iofile.seekg(i+fileEnd); iofile<<ch+32;
}
//---------------------------AA
}

}

读书人网 >C++

热点推荐