C++输入输出

来源:互联网 发布:手机耳机推荐 知乎 编辑:程序博客网 时间:2024/06/18 07:46

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

#include <fstream>

TEXT I/O

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

TEST FILE EXISTENCE

input.fail()

TEST EOF

while(!input.eof()) {    input >> number;    if(input.eof()) break;    // operation}// orwhile(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 charbinaryio.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 Studentbinaryio.read(reinterpret_cast<char*>(&StudentNew), sizeof(Student));

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

0 0