C++的文件读取方式

  • 打开文件
ifstream inputFile;
inputFile.open("input.txt",ios::in);

//第二个参数类似C中的rw
//ios::in     读取
//ios::out    写入
//ios::app    追加写
//ios::binary    以二进制模式打开文件进行读写(图像,视频,音频)
  • 读取文件
string line;
while(std::getline(inputFile,line){
    cout<<line<<endl;
}
//读取文件inputFile到字符串line中
//使用read()方式
std::streamsize length = inputFile.tellg();
inputFile.read(&line[0],length));
cout<<line;
//读取长度为length到line中
//std::istream& read(char *buffer, std::streamsize size);
  • 写入文件
ofstream outputFile;
outputFile.open("output.txt",ios::out);
//利用键盘流进行写
outputFile<<"Hello,world!"<<endl;
//利用string进行写
string content = "hello,world!";
outputFile<<content<<endl;
//向output.txt文件中写入,hello,world
//ifstream和ofstream的区别
//文件打开模式:
//std::ifstream:通常与std::ios::in模式一起使用,表示文件将以输入模式(读取模式)打开。
//std::ofstream:通常与std::ios::out模式一起使用,表示文件将以输出模式(写入模式)打开。
//读写操作:
//std::ifstream:提供了从文件中读取数据的方法,如>>操作符、getline()函数等。
//std::ofstream:提供了向文件中写入数据的方法,如<<操作符、write()函数等。


//使用write方法:std::ostream& write(const char *buffer, std::streamsize size);
const char *data = "Hello, World!";
std::streamsize size = strlen(data);
// 将数据写入文件
outputFile.write(data, size);
//第一个参数:写入源,第二个参数,写入大小
  • 关闭文件
inputFile.close();
  • 检查文件是否打开成功
if (!inputFile.is_open()) {
    std::cerr << "Failed to open input file." << std::endl;
    return 1;
}
  • 设置文件指针位置:设置文件指针位置(也称为文件定位)允许您在文件中移动读取或写入操作的位置
//输入文件流,seekg()指定位置读取
ifstream inputFile("input.txt");
if (!inputFile.is_open()) {
  std::cerr << "Failed to open input file." << std::endl;
  return 1;
}
// 跳过前3行
inputFile.seekg(3 * sizeof(std::string), std::ios::cur);
std::string line;
while (std::getline(inputFile, line)) {
  std::cout << line << std::endl;
}

//输出文件流,seekp()
std::ofstream outputFile("output.txt", std::ios::app);
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open output file." << std::endl;
        return 1;
    }

    // 将文件指针移动到文件末尾
    outputFile.seekp(0, std::ios::end);

    // 在文件末尾追加数据
    outputFile << "This line will be appended to the existing content." << std::endl;


//ios::cur    当前文件指针位置开始
//ios::end    文件末尾
//ios::beg    文件开头
//seekp(),seekg()的第一个参数:偏移量,第二个参数,参考位置,outputFile.seekp(0, std::ios::end);就表示相对end偏移0,也就是最后
  • 获取文件文本大小
inputFile.seekg(0, std::ios::end);
std::streamsize fileSize = inputFile.tellg();//获取当前文件读取指针位置
inputFile.seekg(0, std::ios::beg);
//最后不要忘记把指针放前面
string ss="adfasfa";
std::streamsize length = strlen(ss.c_str());//获取字符串长度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值