#inclass="superseo">clude
#include
using namespace std;
//ASCII读写
void assciiReadWirteFile(const char* readFileName, const char* writeFileName)
{
fstream read(readFileName, ios::in);
fstream write(writeFileName, ios::out);
//流运算符读写, eof()函数返回当前文件是否在文件末尾
//这么写不能读空格
while (!read.eof())
{
char key;
read >> key;
write << key;
}
//使用get 和 put 可以读空格
//while (!read.eof()) {
// char key;
// read.get(key);
// write.put(key);
//}
read.close();
write.close();
}
//二进制读写
void binaryReadWrite(const char* readFileName, const char* writeFileName)
{
//写了两个对象分别是 读 和 写 ,先写框架,关闭这两个文件
fstream readObject(readFileName, ios::in | ios::binary);
fstream writeObject(writeFileName, ios::out | ios::binary);
//判定写入的文件是否为空
while (!readObject.eof())
{
//先写足够的空间 , 1024字节
char str[1024] = "";
//写入文件
readObject.read(str, 1024);
//读文件
writeObject.write(str, 1024);
}
//关闭文件
readObject.close();
writeObject.close();
}
//文件指针偏移
void SeekFile(const char* FileName)
{
fstream fread(FileName, ios::in);
if(!fread)
{
cerr << "open fread lose" << endl;
}
fread.seekg(3);
char key = fread.get();
cout << key << endl;
fread.seekg(0, ios::beg);
cout << fread.get() << endl;
//默认是打印4
//(char)fread.get();
}
int main() {
cerr << "程序异常终止" << endl;
//打开文件测试
fstream file("xxpp.txt", ios::in | ios::out | ios::trunc);
if (!file || !file.is_open())
{
cerr << "文件打开失败" << endl;
}
//关闭测试文件
file.close();
//ASCII 读写操作
assciiReadWirteFile("a.txt", "b.txt");
//二进制读写操作
binaryReadWrite("binaryA.txt", "binaryB.txt");
//文件指针偏移
SeekFile("Seek.txt");
cerr << "程序异常终止" << endl;
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)