码迷,mamicode.com
首页 > 其他好文 > 详细

第15周 程序阅读-二进制及二进制文件的读取3

时间:2015-06-17 09:31:41      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:c++   大一练习   二进制文件   输入输出流   

3、阅读下面的程序,指出其功能,体会seekg()、tellg()等函数的功能及其用法

(1)

#include<iostream>
#include <fstream>
using namespace std;
const char * filename = "a.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;
}

运行结果:

技术分享


(2)

#include <fstream>
using namespace std;
int main (){
    long pos;
    ofstream outfile;
    outfile.open ("test.txt");
    outfile.write ("This is an apple",16);
    pos=outfile.tellp();
    outfile.seekp (pos-7);
    outfile.write (" sam",4);
    outfile.close();
    return 0;
}
运行结果:

技术分享

(3)

#include <iostream> 
#include <fstream> 
using namespace std;
int main() 
{     
    fstream outfile,infile;     
    outfile.open("data.txt",ios::out);     
    for (int i=0;i<26;i++)
       outfile<<(char)('A'+i);     
    outfile.close();     
    infile.open("data.txt",ios::in);     
    char ch;     
    infile.seekg(6,ios::beg);     
    if(infile.get(ch))   
        cout<<ch;     
    infile.seekg(8,ios::beg);     
    if(infile.get(ch))         
        cout<<ch;     
    infile.seekg(-8,ios::end);
    if(infile.get(ch))         
        cout<<ch;         
    cout<<endl;     
    infile.close(); 
    return 0; 
}

运行结果:

技术分享




第15周 程序阅读-二进制及二进制文件的读取3

标签:c++   大一练习   二进制文件   输入输出流   

原文地址:http://blog.csdn.net/ljd939952281/article/details/46529579

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!