C++输入输出

http://www.prglab.com/cms/pages/c-tutorial/file-inputoutput.php

#include <fstream>

TEXT I/O

ofstream output;
output.open("output.txt");
// some operation
output.close(); // close the file

TEST FILE EXISTENCE

input.fail()

TEST EOF

while(!input.eof()) {
    input >> number;
    if(input.eof()) break;
    // operation
}

// or

while(input >> number){
   // operation
}

FORMATTING OUTPUT

#include <iomanip>
// ...
    output << setw(6) << str << endl;

GETLINE, GET, PUT

getline(input, str, '\n');

ch = input.get();
input.get(ch);

output.put(ch);

FILE OPEN MODES

  • ios::in
    为输入(读)而打开文件
  • ios::out
    为输出(写)而打开文件
  • ios::ate
    初始位置:文件尾
  • ios::app
    所有输出附加在文件末尾
  • ios::trunc
    如果文件已存在则先删除该文件
  • ios::binary
    二进制方式

这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如

ofstream out;  
out.open("Hello.txt", ios::in|ios::out|ios::binary);

TESTING STREAM STATE

  • eof()
  • fail()
  • bad()
  • good()
  • clear()

BINARY I/O

WRITE

fstream binaryio("city.dat", ios::out | ios::binary);

string s = "Atlanta";
binaryio.write(s.c_str(), s.size());

int value = 199;
binaryio.write(reinterpret_cast<char*>(&value), sizeof(value));
// Simply performing a binary copy of the value without altering the data, not converting int to char

binaryio.close();

READ

fstream binaryio("city.dat", ios::in | ios::binary);
char s[10];
binaryio.read(s, 10);

int value;
binaryio.read(reinterpret_cast<char*>(&value), sizeof(value));

binary.close();

RANDOM ACCESS FILE

  • seekg()
  • seekp()
Student StudentNew;
binaryio.seekg(2 * sizeof(Student));// move to third Student
binaryio.read(reinterpret_cast<char*>(&StudentNew), sizeof(Student));

参考链接:http://www.jellythink.com/archives/205

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值