2021-10-25 文件读写C++

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;

}

  1. 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();

  2. 设置偏移量
    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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值