美文网首页
c++文件大小

c++文件大小

作者: 送分童子笑嘻嘻 | 来源:发表于2020-02-28 19:52 被阅读0次

为了判断一个文件是否完整
1是获取文件的大小
2是给socket通信加锁,设置flag,锁上,同时flag值为false 锁解开,同时flag值为true

c++文件大小的获取,参考https://blog.csdn.net/marcellen/article/details/49998853

#include <iostream>
#include <fstream>
#include <windows.h>
#include <io.h>
#include <sys\stat.h>
 
 
using namespace std;
 
 
int main()
{
    char *filepath = "D:\\1.TXT";
 
 
    //方法一
    HANDLE handle = CreateFileA( filepath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0 );
    if ( handle != INVALID_HANDLE_VALUE )
    {
        int size = GetFileSize( handle, NULL );
        cout << size << endl;
        CloseHandle( handle );
    }
 
 
    //方法二 C++流获取
    ifstream fin( filepath );
    if( fin.is_open() )
    {
        fin.seekg( 0, ios::end );
        int size = fin.tellg();
        fin.close();
        cout << size << endl;
    }
 
 
    //方法三 C标准获取
    FILE* file = fopen( filepath, "r" );
    if ( file )
    {
        int size = filelength( fileno(file) );
        cout << size << endl;
        fclose( file );
    }
 
 
    //方法四
    struct _stat info;
    _stat(filepath, &info);
    int size = info.st_size;
    cout << size << endl;
 
 
    return 0;
}

相关文章

网友评论

      本文标题:c++文件大小

      本文链接:https://www.haomeiwen.com/subject/xglrhhtx.html