C++提供文件读写类
fstream
#include
ofstream out("…", ios::out);
ifstream in("…", ios::in);
fstream foi("…", ios::in|ios::out);
#include
using namespace std;
int main ()
{
ifstream fr;
ofstream fw;
char word[200], line[200];
fw.open("write.txt");
fr.open("read.txt");
fr >> word; //读取文件,一个单词
fr.getline (line, 100); //读取一行内容
fw << "write file test" << endl;
fw.close();
fr.close();
return 0;
}
-
int v, w, weight;
ifstream infile; //输入流
ofstream outfile; //输出流
infile.open(“G:\C++ project\Read\data.txt”, ios::in);
if(!infile.is_open ())
cout << “Open file failure” << endl;
while (!infile.eof()) // 若未到文件结束一直循环
{
infile >> v >> w >> weight;
cost[v][w] = weight;
cost[w][v] = weight;
}
infile.close(); //关闭文件outfile.open(“G:\C++ project\Read\result.txt”, ios::app); //每次写都定位的文件结尾,不会丢失原来的内容,用out则会丢失原来的内容
if(!outfile.is_open ())
cout << “Open file failure” << endl;
for (int i = 0; i != 10; ++i)
{
for (int j = 0; j != 10; ++j)
{
outfile << i << “\t” << j << “\t” << cost[i][j] << endl; //在result.txt中写入结果
}}
outfile.close(); -
设置偏移量
f.seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。
f.seekp()是对输出文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址
seekg,seekp,到达指定偏移量
tellg,tellp; 当前get/put流的偏移量
file.seekg ( off_type offset, seekdir direction );
file.seekp ( off_type offset, seekdir direction );
// obtaining file size
#include <iostream.h>
#include <fstream.h>const char * filename = “example.txt”;
int main () {
long l,m;
ifstream file (filename, ios::in|ios::binary);
l = file.tellg();
file.seekg (0, ios::end);
m = file.tellg();
file.close();
cout << “size of " << filename;
cout << " is " << (m-l) << " bytes.\n”;
return 0;
}