IT박스

C ++에서 파일 크기를 어떻게 얻을 수 있습니까?

itboxs 2020. 7. 12. 10:22
반응형

C ++에서 파일 크기를 어떻게 얻을 수 있습니까? [복제]


이것에 대한 보완적인 질문을 만들어 봅시다 . C ++에서 파일 크기를 얻는 가장 일반적인 방법은 무엇입니까? 응답하기 전에 이식 가능하고 (유닉스, Mac 및 Windows에서 실행될 수 있음), 신뢰할 수 있고 이해하기 쉽고 라이브러리 종속성이 없는지 확인하십시오 (예 : 부스트 또는 qt는 없지만 휴대용 라이브러리이므로 glib는 괜찮습니다).


#include <fstream>

std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg(); 
}

C ++ 파일에 대한 자세한 내용 http://www.cplusplus.com/doc/tutorial/files/참조 하십시오 .


필자가 가장 인기있는 방법은 아니지만, ftell, fseek 방법이 일부 상황에서 항상 정확한 결과를 제공하지는 않을 수 있다고 들었습니다. 특히 이미 열려있는 파일을 사용하고 크기를 해결해야하고 텍스트 파일로 열리면 잘못된 답변을 제공합니다.

stat가 Windows, Mac 및 Linux에서 c 런타임 라이브러리의 일부이므로 다음 방법은 항상 작동해야합니다.

long GetFileSize(std::string filename)
{
    struct stat stat_buf;
    int rc = stat(filename.c_str(), &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

or 

long FdGetFileSize(int fd)
{
    struct stat stat_buf;
    int rc = fstat(fd, &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

일부 시스템에는 stat64 / fstat64도 있습니다. 따라서 매우 큰 파일에 이것이 필요한 경우 해당 파일을 사용하는 것이 좋습니다.


C ++ 파일 시스템 TS 사용 :

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

int main(int argc, char *argv[]) {
  fs::path p{argv[1]};
  p = fs::canonical(p);

  std::cout << "The size of " << p.u8string() << " is " <<
      fs::file_size(p) << " bytes.\n";
}

fopen (), fseek () 및 ftell () 함수를 사용하여 찾을 수도 있습니다.

int get_file_size(std::string filename) // path to file
{
    FILE *p_file = NULL;
    p_file = fopen(filename.c_str(),"rb");
    fseek(p_file,0,SEEK_END);
    int size = ftell(p_file);
    fclose(p_file);
    return size;
}

#include <stdio.h>
int main()
{
    FILE *f;
    f = fopen("mainfinal.c" , "r");
    fseek(f, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(f);
    printf("%ld\n", len);
    fclose(f);
}

C ++에서는 다음 함수를 사용할 수 있으며 파일 크기를 바이트 단위로 반환합니다.

#include <fstream>

int fileSize(const char *add){
    ifstream mySource;
    mySource.open(add, ios_base::binary);
    mySource.seekg(0,ios_base::end);
    int size = mySource.tellg();
    mySource.close();
    return size;
}

아래 코드 스 니펫은이 게시물의 질문을 정확하게 해결합니다. :)

///
/// Get me my file size in bytes (long long to support any file size supported by your OS.
///
long long Logger::getFileSize()
{
    std::streampos fsize = 0;

    std::ifstream myfile ("myfile.txt", ios::in);  // File is of type const char*

    fsize = myfile.tellg();         // The file pointer is currently at the beginning
    myfile.seekg(0, ios::end);      // Place the file pointer at the end of file

    fsize = myfile.tellg() - fsize;
    myfile.close();

    static_assert(sizeof(fsize) >= sizeof(long long), "Oops.");

    cout << "size is: " << fsize << " bytes.\n";
    return fsize;
}

참고URL : https://stackoverflow.com/questions/5840148/how-can-i-get-a-files-size-in-c

반응형