1. 输入输出 I/O 流
C: fopen/fclose/fread/fwrite/fprintf/fscanf/fseek/ftell/fput/fget...
C++: 对基本的 I/O 操作做了类的封装,其功能没有任何差别,用法也相似;
2. 格式化 I/O 流:<< / >>
#include <iostream>
#include <fstream> // 打开文件
using namespace std;
int main() {
// 写文件:
ofstream ofs("hello.txt"); // 创建文件,类似于 fopen 用 w 模式,只读且清空
// ofs 在 ofstream 的构造函数里面被构造,打开成功返回 ture,失败返回 false,是 bool 型;
if(! ofs) {
perror("error"); // perror 打印出错信息;
return -1;
}
ofs << "hello word!" << endl; // hello word! 被输入文件 hello.txt 里;
ofs.close();
ofs.open("hello.txt", ios::app); // 打开文件,追加内容,类似于 fopen 的 a 模式
if(! ofs) {
perror("error");
return -1;
}
ofs << "another\n";
ofs.close();
// 读文件:
ifstream ifs("hello.txt");
if(! ifs) {
perror("error");
return -1;
}
steing s1, s2;
ifs >> s1 >> s2; // 读入上面输入的两个字符串;以空白字符作为分隔(空格、换行、制表);
return 0;
}
ios::app 以追加的方式打开文件;
ios::ate 文件打开后定位到文件尾;
ios::binary 以二进制方式打开文件;缺省是文本方式;
ios::in 以输入方式打开;
ios::out 以输出方式打开;
ios::nocreate 不建立文件,所以文件不存在时,打开失败;
ios::noreplace 不覆盖文件,所以打开文件时,如果文件存在则失败;
ios::trunc 如果文件存在,把文件长度设为 0;
ios::beg 移动到文件头;
ios::cure 移动到文件当前位置;
ios::end 移动到文件尾;
可以用 或 把以上文件属性连接起来:
3. 非格式化 I/O 流:put/get
#include <iostream>
#include <fstream>
using namespace std;
int mian() {
// 输入
ofstream ofs("putget.txt");
if(! ofs) {
perror("error");
return -1;
}
for(char c = ' '; c <= '~'; ++c) // 把 ASIIC 表里的字符从第一个到最后一个写入;
// 前++返回引用,后++返回副本,所以建议用前++,效率高;
if(! ofs.put(c)) {
preeor("error");
return -1;
&n
C: fopen/fclose/fread/fwrite/fprintf/fscanf/fseek/ftell/fput/fget...
C++: 对基本的 I/O 操作做了类的封装,其功能没有任何差别,用法也相似;
2. 格式化 I/O 流:<< / >>
#include <iostream>
#include <fstream> // 打开文件
using namespace std;
int main() {
// 写文件:
ofstream ofs("hello.txt"); // 创建文件,类似于 fopen 用 w 模式,只读且清空
// ofs 在 ofstream 的构造函数里面被构造,打开成功返回 ture,失败返回 false,是 bool 型;
if(! ofs) {
perror("error"); // perror 打印出错信息;
return -1;
}
ofs << "hello word!" << endl; // hello word! 被输入文件 hello.txt 里;
ofs.close();
ofs.open("hello.txt", ios::app); // 打开文件,追加内容,类似于 fopen 的 a 模式
if(! ofs) {
perror("error");
return -1;
}
ofs << "another\n";
ofs.close();
// 读文件:
ifstream ifs("hello.txt");
if(! ifs) {
perror("error");
return -1;
}
steing s1, s2;
ifs >> s1 >> s2; // 读入上面输入的两个字符串;以空白字符作为分隔(空格、换行、制表);
return 0;
}
ios::app 以追加的方式打开文件;
ios::ate 文件打开后定位到文件尾;
ios::binary 以二进制方式打开文件;缺省是文本方式;
ios::in 以输入方式打开;
ios::out 以输出方式打开;
ios::nocreate 不建立文件,所以文件不存在时,打开失败;
ios::noreplace 不覆盖文件,所以打开文件时,如果文件存在则失败;
ios::trunc 如果文件存在,把文件长度设为 0;
ios::beg 移动到文件头;
ios::cure 移动到文件当前位置;
ios::end 移动到文件尾;
可以用 或 把以上文件属性连接起来:
3. 非格式化 I/O 流:put/get
#include <iostream>
#include <fstream>
using namespace std;
int mian() {
// 输入
ofstream ofs("putget.txt");
if(! ofs) {
perror("error");
return -1;
}
for(char c = ' '; c <= '~'; ++c) // 把 ASIIC 表里的字符从第一个到最后一个写入;
// 前++返回引用,后++返回副本,所以建议用前++,效率高;
if(! ofs.put(c)) {
preeor("error");
return -1;
&n