// 程序在VC6.0下测试成功
#include
#include
void Write(ofstream &out, unsigned int num, unsigned int count, unsigned int data);
void Modify(char *fname, unsigned int num, unsigned int data);
void Print(char *fname);
int main()
{
bool bModify = true;
// 输出数据
ofstream out("key.dat",ios::out);
if(!out)
{
cerr<<"The file key.dat does not exist.\n";
bModify = false;
}
for(int i=0; i<10; i++) // 向key.dat文件输出10行初始数据
Write(out,i,0,0);
cout<<"Finish output the data.\n\n";
out.close();
Print("key.dat"); // 输出文件内容
// 修改数据
if(bModify)
{
unsigned int N,S;
while(1)
{
cout<<"\nEnter the num(N) and the data(S):\n";
cout<<"N:";
cin>>N;
if(N == -1) // 输入-1退出修改状态
return 0;
cout<<"S:";
cin>>S;
Modify("key.dat", N, S);
Print("key.dat"); // 输出文件内容
}
}
return 0;
}
void Write(ofstream &out, unsigned int num, unsigned int count, unsigned int data)
{
// 由于unsigned int取值范围为:0 ~ 4294967295,11个空格间隔可以在修改的时候不影响后面的数据
if(out)
out<
void Modify(char *fname, unsigned int num, unsigned int data)
{
fstream stream(fname,ios::in | ios::out);
if(!stream)
cerr<<"The file key.dat does not exist.\n";
else
{
stream.seekg(0,ios::beg); // 将文件指针移到起始位置
unsigned int n,c,s;
while(!stream.eof())
{
int pos = stream.tellg();
stream>>n>>c>>s; // 读取数据
if(n == num)
{
stream.seekp(pos,ios::beg);
stream<<"\n"<
}
}
stream.close();
}
}
void Print(char *fname)
{
ifstream in(fname,ios::in);
if(in)
{
unsigned int n,c,s;
in.seekg(0,ios::beg); // 将文件指针移到起始位置
while(!in.eof())
{ n = c = s = -1;
in>>n>>c>>s; // 读取数据,使用>>重载符可以跳过空格
if(n != -1)
cout<
in.close();
}
}
//请把你的文件和程序放在一个文件夹中
//正确程序如下:
#include
#include
using namespace std;
int main()
{
ifstream file;
int a;
file.open("hello.txt",ios::in);
file1>>a;
cout< return 0;
}