当前位置:网站首页>Seekg, tellg related file operations

Seekg, tellg related file operations

2022-06-12 13:30:00 Boring ah le

seekg() And tellg() Related file operations
Operate on the input stream :seekg() And tellg()
Operate on the output stream :seekp() And tellp()
The following uses the input stream function as an example :
seekg() Is to locate the input file , It has two parameters : The first parameter is the offset , The second parameter is the base address .
For the first parameter , It can be a positive or negative value , Positive indicates a backward offset , Negative indicates forward offset . The second parameter can be :
ios::beg: Indicates the starting position of the input stream
ios::cur: Indicates the current position of the input stream
ios::end: Indicates the end position of the input stream
tellg() The function does not need to take arguments , It returns the position of the current positioning pointer , It also represents the size of the input stream .

The procedure is :


#include <iostream>
#include <fstream>
#include <assert.h>

using namespace std;
int main()
{
    
    ifstream in("test.txt");
    assert(in);
  
    in.seekg(0,ios::end);       // The base address is at the end of the file , The offset address is 0, So the pointer is at the end of the file 
    streampos sp=in.tellg(); //sp Position pointer for , Because it's at the end of the file , So that's the size of the file 
    cout<<"file size:"<<endl<<sp<<endl;

    in.seekg(-sp/3,ios::end); // The base address is the end of the file , The offset address is negative , So move forward sp/3 Bytes 
    streampos sp2=in.tellg();
    cout<<"from file to point:"<<endl<<sp2<<endl;

    in.seekg(0,ios::beg);        // Base address is file header , The offset for the 0, So it is located in the file header 
    cout<<in.rdbuf();             // Read the contents of the file from the beginning 
    in.seekg(sp2);

    cout<<in.rdbuf()<<endl; // from sp2 Start reading the contents of the file 

    return 0;
}
int main()
{
    
 // Get the file size :C++ The way 
 ifstream ifs;
 ifs.open("log.txt");
 assert(ifs.is_open());
 ifs.seekg( 0 , std::ios::end );
 cout<<ifs.tellg()<<endl;
 ifs.close();

 //  Get the file size :C The way 
 FILE* fp = fopen("log.txt", "rb");
 assert ( 0 == fseek(fp, 0, SEEK_END));
 unsigned int usize = ftell(fp);
 cout<<usize<<endl;
 fclose(fp);

 return 0;
}
原网站

版权声明
本文为[Boring ah le]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010516317099.html