栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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++ projectReaddata.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++ projectReadresult.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
    #include

    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;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353128.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号