ios::in: 文件以输入方式打开
ios::out: 文件以输出方式打开
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary
用与 把以上属性连接起来,如ios::out+ios::binary
打开文件的属性取值是:
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
可以用“或”或者“+”把以上属性连接起来 ,如3或1|2就是以只读和隐含属性打开文件。
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
按特定字符读取文本 ===================== #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream op; op.open("123.txt", ios::in); if(op.fail()) throw runtime_error("Open file error!!!"); char buf[256]; while(!op.eof()) { op.getline(buf,256,'\n'); //按行读取 op.getline(buf,256,' ');//按空格读取 op.getline(buf,256,'a');//遇到a则重新开始读取下一个字符串 cout<<buf<<endl; } op.close(); return 0; } 按照单词读取字符串 ====================================== #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream op; ifstream ifs("123.txt"); string str; while(ifs>>str) { cout<<str<<endl; } return 0; }
写文件
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ofstream in; in.open("123.txt", ios::trunc); int i; char a = 'a'; for(i = 1; i <= 26; i ++) { if(i < 10) in<<"0"<<i<<"\t"<<a<<endl; else in<<i<<"\t"<<a<<endl; a ++; } in.close(); return 0; }
读文件操作:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream op; op.open("123.txt", ios::in); if(op.fail()) throw runtime_error("Open file error!!!"); char buf[256]; while(!op.eof()) { op.getline(buf,256,'\n'); cout<<buf<<endl; } op.close(); return 0; }
// Cluster.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { /*fstream op; op.open("E:\\123.txt", ios::in); if(op.fail()) throw runtime_error("Open file error!!!"); char buf[256]; while(!op.eof()) { op.getline(buf,256,'\n'); cout<<buf<<endl; } op.close();*/ /*int count = 0; FILE* fp; char str[100]; fp = fopen("E:\\123.txt", "r"); while (fscanf(fp, "%s", str) != EOF) { printf("%s\n", str); count++; } fclose(fp);*/ ifstream ifs("E:\\123.txt"); string str; int count = 0; while (ifs >>str) { cout << str << endl; count++; } ifs.close(); return 0; }