30/09/2018, 20:35
Đọc-ghi files struct vào files trong C++ dùng hàm fstream
Khi mình in ra màn hình thi lỗi.
Đây là source của mình
#include <iostream>
#include <fstream>
#include <cstring>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAX 100
using namespace std;
struct Test{
string item;
int quantity;
double cost;
};
void Nhap(Test &);
void NhapDanhSach(Test [], int *);
void Xuat (Test );
void XuatDanhSach (Test [], int );
void Write (Test [], int );
void Read (Test [], int &);
void Nhap (Test &x)
{
cout << "Nhap item: ";
getline (cin, x.item);
cout << "Nhap quatity: ";
cin >> x.quantity;
cout << "Nhap cost: ";
cin >> x.cost;
//Write(x);
cin.ignore();
}
void NhapDanhSach(Test a[], int *n)
{
cout << "Nhap n: ";
cin >> *n;
cin.ignore();
for (int i=0; i<(*n); i++)
{
cout << "---- Test " << i << "----" << endl;
Nhap (a[i]);
cout << endl;
}
}
void Xuat (Test a)
{
cout << a.item << " | " << a.quantity << " | " << a.cost << endl;
}
void XuatDanhSach (Test a[], int n)
{
cout << "===== In danh sach =====" << endl;
for (int i=0; i<n; i++)
Xuat (a[i]);
cout << endl;
}
void Write (Test x[], int n)
{
ofstream ghi ("Test_5", ios::out |ios::app | ios::binary);
if (!ghi){
cout << "Cannot open file." << endl;
return ;
}
for (int i=0; i<n; i++)
ghi.write((const char *) &x[i], sizeof(Test));
ghi.close();
if (!ghi.good())
{
cout << "A file error occurred" << endl;
return ;
}
}
void Read (Test a[], int &n)
{
ifstream doc ("Test_5", ios::in | ios::binary);
if (!doc){
cout << "Cannot open file" << endl;
return ;
}
while (!doc.eof())
{
doc.read((char *) &a[n], sizeof(Test));
n++;
}
doc.close();
if (!doc.good())
{
cout << "A file error occurred" << endl;
return ;
}
}
int main(int argc, char** argv) {
/*
ofstream fout ("InvDat", ios::out | ios::binary);
if (!fout)
{
cout << "Cannot open file.
" << endl;
return 1;
}
*/
Test a[MAX];
int n=0;
NhapDanhSach(a, &n);
//Write(a, n);
XuatDanhSach (a, n);
/*
for (int i=0; i<n; i++)
fout.write((const char *) &a[i], sizeof(Test));
fout.close();
if (!fout.good())
{
cout << "A file error occurred." << endl;
return 1;
}
*/
/*
ifstream fin ("InvDat", ios::in | ios::binary);
if (!fin){
cout << "Cannot open file.
" << endl;
return 1;
}
*/
Test b[MAX];
int m=0;
Read(b, m);
XuatDanhSach(b, m);
/*
for (int i=0; i<n; i++)
fin.read((char *) &b[i], sizeof(Test));
fin.close();
if (!fin.good()){
cout << "A file error occurred." << endl;
return 1;
}
for (int i=0; i<n; i++)
Xuat(b[i]);
*/
return 0;
}
‘’’
Bài liên quan