c++读写文件

创建文件并写入字符串

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	//写入
	ofstream fout("C:/Users/94894/Desktop/test.txt", ios::out);
	if (!fout) {
		cout << "error, the file not exiest" << endl;
		exit(1);
	}
	fout << "this is a line of test words";
	fout.close();
	return 0;

}

读取文件中的内容

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	//读取
	ifstream fin("C:/Users/94894/Desktop/test.txt", ios::in);
	if (!fin) {
		cout << "error, the file not exiest" << endl;
		exit(1);
	}
	char str[80];
	fin.getline(str, 80);//读取80个字符
	//fin >> str;//逐个读取,用空格划分
	cout << str << endl;
	fin.close();

}

读写二进制文件

#include <iostream>
#include <fstream>
using namespace std;

int cput() {
	ofstream outf("C:/Users/94894/Desktop/test.txt", ios::binary);
	if (!outf) {
		cout << "Cannot open output file.\n";
		exit(1);
	}
	char ch = 'a';
	for (int i = 0; i < 26; i++) {
		outf.put(ch);
		ch++;
	}
	cout << "ok" << endl;
	outf.close();
	return 0;
}

int cget() {
	ifstream inf("C:/Users/94894/Desktop/test.txt", ios::binary);
	if (!inf) {
		cout << "Cannot open input file.\n";
		exit(1);
	}
	char ch;
	while (inf.get(ch)) {
		cout << ch;
	}
	inf.close();
	return 0;
}

int main() {
	cput();
	cget();   

	return 0;
}

用read()函数和write()函数读写二进制文件

inf.read(char *buf, int len);
outf.write(const char *buf, int len);

写入:

#include <iostream>
#include <fstream>
using namespace std;

struct list{
	char course[15];
	int score;
};

int main() {
	list ob[2] = {"Computer", 90, "History", 99};
	ofstream out("test.txt", ios::binary);
	if (!out) {
		cout << "Cannot open output file.\n";
		abort();   //退出程序,作用与exit相同。
	}
	for (int i = 0; i < 2; i++) {
		out.write((char*) &ob[i], sizeof(ob[i]));
	}
	out.close();

	return 0;
}

读取:

#include <iostream>
#include <fstream>
using namespace std;

struct list{
	char course[15];
	int score;
};

int main() {
	list ob[2];
	ifstream in("test.txt", ios::binary);
	if (!in) {
		cout << "Cannot open input file.\n";
		abort();
	}
	for (int i = 0; i < 2; i++) {
		in.read((char *) &ob[i], sizeof(ob[i]));
		cout << ob[i].course << " " << ob[i].score << endl; 
	}
	in.close();

	return 0;
}

检测文件结束

文件结束的地方有一个标志位EOF。文件流方式读取文件时,使用成员函数eof()可以检测到这个结束符。如果该函数的返回值非零,表示到达文件尾。返回值为零表示未达到文件尾。该函数的原型是:

int eof();
函数eof()的用法示例如下:
ifstream ifs;
···
if (!ifs.eof())   //尚未到达文件尾
    ···
还有一个检测方法就是检查该流对象是否为零,为零表示文件结束。
ifstream ifs;
···
if (!ifs)
    ···
如下例子:
while (cin.get(ch))
    cut.put(ch);
这是一个很通用的方法,就是检测文件流对象的某些成员函数的返回值是否为0,为0表示该流(亦即对应的文件)到达了末尾。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值