2 qq 32742637 qq_32742637 于 2016.04.23 20:01 提问

求大神赐教,关于文件读写,fun1正常fun2就会输出乱码
c++

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
using namespace std;
class Worker
{
public:
int num;
char name[20];
int age;
int wage;
};
Worker work[5] = { 12, "Zhang", 22, 10000, 4, "Li", 23, 1000, 2, "Fan", 52, 100, 8, "Wu", 24, 10, 6, "Ha", 28, 12000 };
void swap(Worker worker[], int i, int j)
{
int temp1, temp2, temp3;
char temp4[20];
temp1 = worker[i].num;
temp2 = worker[i].age;
temp3 = worker[i].wage;
strcpy(temp4, worker[i].name);
worker[i].num = worker[j].num;
worker[i].age = worker[j].age;
worker[i].wage = worker[j].wage;
strcpy(worker[i].name, worker[j].name);
worker[j].num = temp1;
worker[j].age = temp2;
worker[j].wage = temp3;
strcpy(worker[j].name, temp4);

}
void fun1() //将5个工人数据写入到文件,fun1函数正常
{
ofstream outfile("work.txt", ios::out);
if (!outfile)
{
cerr << "open error!" << endl;
abort();
}
outfile.close();
fstream iofile("work.txt", ios::out | ios::in | ios::binary);
if (!iofile)
{
cerr << "open error!" << endl;
abort();
}
for (int i = 0; i < 4; i++)
{
for (int j = i; j < 4; j++)
{
if (work[i].num > work[j + 1].num)
{
swap(work, i, j);
}
}
}
for (int i = 0; i < 5; i++)
{
iofile.write((char )&work[i], sizeof(work[i]));
iofile.seekg(i*sizeof(work[i]), ios::beg);
iofile.read((char *)&work[i], sizeof(work[i]));
cout << work[i].num << " " << work[i].name << " " << work[i].age << " " << work[i].wage << endl;
}
iofile.close();
}
void fun2()//输出乱码,为什么
{
ofstream outfile("work.txt", ios::app|ios::binary);
if (!outfile)
{
cerr << "open error!" << endl;
abort();
}
Worker worker[2] = { 101, "Lin", 72, 10800, 104, "Ka", 29, 10020 };
for (int i = 0; i < 2; i++)
{
outfile.write((char
)&worker[i], sizeof(worker[i]));
}
outfile.close();
Worker all_work[7];
ifstream infile("work.txt", ios::in|ios::binary);
if (!infile)
{
cerr << "open error!" << endl;
abort();
}
for (int i = 0; i < 7; i++)
{
infile.seekg(i*sizeof(all_work[i]), ios::beg);
infile.read((char*)&all_work[i], sizeof(all_work[i]));
cout << all_work[i].num << " " << all_work[i].name << " " << all_work[i].age << " " << all_work[i].wage << endl;
}
infile.close();
}
void main()
{
fun1();
fun2();
system("pause");
}

1个回答

qq423399099
qq423399099   Ds   Rxr 2016.04.23 20:24
已采纳

确定你的iofile.write((char )&work[i], sizeof(work[i]));是对的?
而不是iofile.write((char *)&work[i], sizeof(work[i])); ?

qq_32742637
qq_32742637 回复小灸舞: 刚才找到原因了,不知道为什么,我这里复制粘贴总是会漏掉星号。哈哈。谢啦
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!