读书人

文件输入输出有关问题

发布时间: 2012-02-08 19:52:21 作者: rapoo

文件输入输出问题
下面程序只能把s1内容写到文件中,却不能从文件中读不出来,请问哪里错了?
#include <iostream>
#include <conio.h>
#include <fstream>


using namespace std;

int main()
{ofstream out( "a.txt ");
ifstream in( "a.txt ");
string s1,s2;

s1= "abcd 1234\n ";
out < <s1;
in> > s2;

cout < < "s2= " < <s2 < <endl;//s2为空~~~~

out.close();
in.close();
getch();
return 0;
}



[解决办法]
搂主试试在输入之前关闭输出流
关闭输出流前文件应该是空的
或者这样
ifstream in( "filename ",ios::in|ios::out);
ostream out(in.rabuf());
这样输入输出流将使用同一个缓冲区
即使未写入文件,也可以将它读出来(读自缓冲区)
[解决办法]
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ofstream ofile( "a.txt ");//建立输入输出文件流
string s1,s2;

s1= "abcd 1234\n ";
if(!ofile)
{
cout < < "cannot open! " < <endl;
return 1;
}

ofile < < s1;
ofile.close();
ifstream ifile( "a.txt ");
if(!ifile)
{
cout < < "cannot open! " < <endl;
return 1;
}
getline(ifile,s2);
ifile.close();
cout < < "s2= " < <s2 < <endl;


getch();
return 0;
}
[解决办法]
// io/rw1. cpp

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
// open file "example.dat " for reading and writing
filebuf buffer;
ostream output(&buffer);
istream input(&buffer);
buffer.open ( "example.dat ", ios::in | ios::out | ios::trunc);

for (int i=1; i <=4; i++) {
// write one line
output < < i < < ". line " < < endl;

// print all file contents
input.seekg(0); //seek to the beginning
char c;
while (input.get(c)) {
cout.put(c);
}
cout < < endl;
input.clear(); //clear eofbit and failbit
}
}


The output of the program is as follows:


1. line

1. line
2. line

1. line
2. line
3. line

1. line
2. line
3. line
4. line


[解决办法]
用fstream这样吧

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open( "a.txt ",ios::out|ios::app);
if(!myfile)
{
cout < < "文件错误! " < <endl;
system( "pause ");
exit(1);
}
myfile < < "new add " < <endl < < "网址;
myfile.close(); //注意关闭



myfile.open( "a.txt ",ios::in);
if(!myfile)
{
cout < < "文件读错误! " < <endl;
system( "pause ");
exit(1);
}
char ch;
while(myfile.get(ch))
{
cout.put(ch);
}
myfile.close();
system( "pause ");
}

读书人网 >C++

热点推荐