创建文件并写入字符串
#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表示该流(亦即对应的文件)到达了末尾。