c++文件的读写
1、写文件
ofstream out;
out.open("Hello.txt", ios::in|ios::out|ios::binary)
竖线表示 或 。 其中open也可以省略,out以默认方式打开文件。
2、读文件
- get()读入一个字符 char c;c=infile.get();
- 使用get(char *,int n,char delim=’\n’)一次读多个字符;
- 使用read(char *,int n)读文件;
// reading a text file
#include <iostream>
#include <fstream>
#include<stdlib.h>
using namespace std;
int main () {
char buffer[256];
ifstream examplefile ("example.txt");
if (! examplefile.is_open())
{ cout << "Error opening file"; exit (1); }
while (! examplefile.eof() ) {
examplefile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
//如果是个很大的多行存储的文本型文件可以这么读:
char buf[1024]; //临时保存读取出来的文件内容
string message;
ifstream infile;
infile.open("myfile.js");
if(infile.is_open()) //文件打开成功,说明曾经写入过东西
{
while(infile.good() && !infile.eof())
{
memset(buf,0,1024);
infile.getline(buf,1204);
message = buf;
...... //这里可能对message做一些操作
cout<<message<<endl;
}
infile.close();
}
3、写读流的部分函数与名词
通过移动文件读写指针,可在文件指定位置进行读写。
seekg(绝对位置); //绝对移动, //输入流操作
seekg(相对位置,参照位置); //相对操作
tellg(); //返回当前指针位置
seekp(绝对位置); //绝对移动, //输出流操作
seekp(相对位置,参照位置); //相对操作
tellp(); //返回当前指针位置
参照位置:
ios::beg = 0 //相对于文件头
ios::cur = 1 //相对于当前位置
ios::end = 2 //相对于文件尾
、
其它。。。。。
读写二进制文件注意事项
打开方式中必须指定ios::binary,否则读写会出错
用read\write进行读写操作,而不能使用插入、提取运算符进行操作,否则会出错。
使用eof()函数检测文件是否读结束,使用gcount()获得实际读取的字节数