#include <iostream>
using namespace std;
int main()
{
cout << 1 << endl;
cerr << 2 << endl;
clog << 3 << endl;
cout.put('I');
cout << endl;
cout.write("I love you", 8);
cout << endl;
system("pause");
return 0;
}
#include<iostream>
#include <fstream> //加上这样一个头文件,文件操作
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
if (!file)
{
cout << "打开文件失败" << endl;
exit(0);
}
file << "I love you" << endl;
file << "but you don't love me" << endl;
file.close();
fstream file1;
file1.open("test.txt", ios::in);
if (!file1)
{
cout << "打开文件失败" << endl;
exit(0);
}
char str[100];
while (!file1.eof())
{
file1.getline(str, sizeof(str));
cout << str << endl;
}
file1.close();
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct student
{
char name[10];
int num;
int age;
char sex;
};
int main()
{
student mystudent[3] = { "victor", 1001, 98, 'w',
"我爱学习", 1002, 1, 'w',
"落尘孤鹜", 1003, 55, 'm' };
//fstream---ofstream---ifstream
ofstream outfile("file.txt", ios::binary);
if (!outfile)
{
cerr << "打开文件失败" << endl;
return 0;
}
for (int i = 0; i < 3; i++)
{
//write("指针",大小)
outfile.write((char *)&mystudent[i], sizeof(mystudent[i]));
}
outfile.close();
ifstream infile("file.txt", ios::binary);
if (!infile)
{
cerr << "打开文件失败" << endl;
return 0;
}
student stu[3];
for (int i = 0; i < 3; i++)
{
infile.read((char *)&stu[i], sizeof(stu[i]));
}
infile.close();
cout << setw(10) << "姓名"
<< setw(7) << "学号"
<< setw(6) << "年龄"
<< setw(6) << "性别" << endl;
for (int i = 0; i < 3; i++)
{
cout << setw(10) << stu[i].name;
cout << setw(7) << stu[i].num;
cout << setw(6) << stu[i].age;
cout << setw(6) << stu[i].sex << endl;
}
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
char name[10];
int num;
int age;
};
student stu[5] =
{
"哇哦", 1001, 18,
"孤鹜", 1002, 19,
"闲者", 1003, 20,
"路伴", 1004, 21,
"victor", 1005, 22
};
int main()
{
student mystudent;
fstream file;
//ios::binary 二进制形式
file.open("file.txt", ios::out | ios::in | ios::binary);
if (!file)
{
cerr << "打开文件失败" << endl;
exit(0);
}
for (int i = 0; i < 5; i++)
{
file.write((char *)&stu[i], sizeof(student)); //写的方式是怎样
}
file.seekp(sizeof(student)* 4); //移动到第5个人位置
file.read((char*)&mystudent, sizeof(student));
cout << mystudent.name << "\t" << mystudent.num << "\t" << mystudent.age<<endl;
file.seekp(sizeof(student)* 1, ios::beg);
file.read((char*)&mystudent, sizeof(student));
cout << mystudent.name << "\t" << mystudent.num << "\t" << mystudent.age << endl;
file.close();
system("pause");
return 0;
}