반응형
C ++ 파일 스트림 (fstream)을 사용하여 파일 크기를 어떻게 결정할 수 있습니까?
이 질문에 이미 답변이 있습니다.
매뉴얼에서 이것을 놓친 것 같지만 헤더 istream
에서 C ++의 클래스를 사용하여 파일 크기 (바이트)를 어떻게 결정 fstream
합니까?
ios::ate
플래그 (및 ios::binary
플래그)를 사용하여 파일을 열 수 있으므로 tellg()
함수는 파일 크기를 직접 제공합니다.
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
끝까지 찾은 다음 차이를 계산할 수 있습니다.
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
tellg
파일의 정확한 크기를 결정하는 데 사용하지 마십시오 . 로 결정된 길이 tellg
는 파일에서 읽을 수있는 문자 수보다 큽니다.
stackoverflow 질문 tellg () 함수에서 잘못된 파일 크기를 제공합니까? tellg
파일의 크기 나 시작 부분의 오프셋 (바이트)을보고하지 않습니다. 나중에 동일한 위치를 찾는 데 사용할 수있는 토큰 값을보고합니다. (유형을 정수 유형으로 변환 할 수 있다는 보장조차 없습니다.) Windows (및 대부분의 비 Unix 시스템)의 경우 텍스트 모드에서는 tellg가 반환하는 내용과 해당 위치에 도달하기 위해 읽어야하는 바이트 수 사이에 직접적이고 즉각적인 매핑이 없습니다.
읽을 수있는 바이트 수를 정확히 아는 것이 중요하다면, 그렇게하는 유일한 방법은 읽는 것입니다. 다음과 같이이 작업을 수행 할 수 있어야합니다.
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
이렇게 :
long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;
나는 초보자이지만 이것은 내가 그것을하는 방법을 스스로 배운 것입니다.
ifstream input_file("example.txt", ios::in | ios::binary)
streambuf* buf_ptr = input_file.rdbuf(); //pointer to the stream buffer
input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()
size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.
반응형
'Programing' 카테고리의 다른 글
v-model이 변경 될 때 이벤트를 발생시키는 방법은 무엇입니까? (0) | 2020.10.26 |
---|---|
자주 실행되도록 작업을 어떻게 설정합니까? (0) | 2020.10.26 |
C는 오픈 소스입니까? (0) | 2020.10.26 |
Android에서 EditText를 비활성화하는 방법 (0) | 2020.10.26 |
프로세스가 시작될 때까지 Process.Start 대기 만들기 (0) | 2020.10.26 |