为什么 ios::app(追加)在 C++ 中不起作用?
Why is ios::app (append) not working in C++?
我在 Code::Blocks 中使用 GNU C++。
在下面的代码中,我使用 ios::app 在文件 "employee.txt" 的末尾追加数据。该代码在 Turbo C++ 中运行良好,但 GNU C++ 似乎造成了一些麻烦。文件中未存储任何数据。可能的原因和解决方法是什么?
编辑 - 在尝试了此处给出的解决方案后,它起作用了,但现在又出现了同样的问题。即使输入数据后,文件仍然是空的。我已经更新了代码。
if(ch==1)
{
cout<<"Enter Data for employee\n";
e.getdata();
f.open("employee.txt", ios::app|ios::binary);
f.write((char*)&e, sizeof(employee));
f.close();
}
if(ch==2)
{
int en;
int flag=0;
cout<<"Enter Employee No. to search\n";
cin>>en;
f.open("employee.txt", ios::in | ios::binary );
f.read((char*)&e, sizeof(e));
while(f)
{
if(e.reteno()==en)
{
flag=1;
e.putdata();
}
f.read((char*)&e, sizeof(e));
}
if(flag==0)
{
cout<<"Record Not Found\n";
}
f.close();
}
在分支 ch==1
中,您应该指定 ios::app
以添加记录。即 ios::app|ios::out|ios::binary
阅读时,不要指定ios::app
,因为您想从头开始阅读。而是使用 ios::in|ios::binary
也就是说,您可能不想使用 read/write,而是使用 <<
和 >>
来读取和写入文件。
例如
ofstream& operator<<(ofstream& f, const employee& e)
{
f << e.eno << ',' << e.name << ',' << e.balance;
return f;
}
...
f << e;
在 ios::app
模式下打开要读取的文件没有意义,因为 ios::app
会将您的文件指针移动到文件末尾,因此无论您添加什么都会附加到它.
在 ch == 1
中使用 f.open ("employee.txt", ios::app | ios::binary);
。这将打开文件供您追加。
在 ch == 2
中使用 f.open("employee.txt", ios::in | ios::binary)
。这将打开文件供您阅读。
我在 Code::Blocks 中使用 GNU C++。 在下面的代码中,我使用 ios::app 在文件 "employee.txt" 的末尾追加数据。该代码在 Turbo C++ 中运行良好,但 GNU C++ 似乎造成了一些麻烦。文件中未存储任何数据。可能的原因和解决方法是什么?
编辑 - 在尝试了此处给出的解决方案后,它起作用了,但现在又出现了同样的问题。即使输入数据后,文件仍然是空的。我已经更新了代码。
if(ch==1)
{
cout<<"Enter Data for employee\n";
e.getdata();
f.open("employee.txt", ios::app|ios::binary);
f.write((char*)&e, sizeof(employee));
f.close();
}
if(ch==2)
{
int en;
int flag=0;
cout<<"Enter Employee No. to search\n";
cin>>en;
f.open("employee.txt", ios::in | ios::binary );
f.read((char*)&e, sizeof(e));
while(f)
{
if(e.reteno()==en)
{
flag=1;
e.putdata();
}
f.read((char*)&e, sizeof(e));
}
if(flag==0)
{
cout<<"Record Not Found\n";
}
f.close();
}
在分支 ch==1
中,您应该指定 ios::app
以添加记录。即 ios::app|ios::out|ios::binary
阅读时,不要指定ios::app
,因为您想从头开始阅读。而是使用 ios::in|ios::binary
也就是说,您可能不想使用 read/write,而是使用 <<
和 >>
来读取和写入文件。
例如
ofstream& operator<<(ofstream& f, const employee& e)
{
f << e.eno << ',' << e.name << ',' << e.balance;
return f;
}
...
f << e;
在 ios::app
模式下打开要读取的文件没有意义,因为 ios::app
会将您的文件指针移动到文件末尾,因此无论您添加什么都会附加到它.
在 ch == 1
中使用 f.open ("employee.txt", ios::app | ios::binary);
。这将打开文件供您追加。
在 ch == 2
中使用 f.open("employee.txt", ios::in | ios::binary)
。这将打开文件供您阅读。