1. 程式人生 > >C++檔案讀寫之獲取檔案大小的幾種常見的方式

C++檔案讀寫之獲取檔案大小的幾種常見的方式

對檔案操作時有時獲得檔案的大小時必要的.下面是獲得其大小小的較簡單方法.
#include<io.h> //C語言標頭檔案
#include<iostream> //for system();
using namespace std;
int main()
{
int handle;
handle = open("test.txt", 0x0100); //open file for read
long length = filelength(handle); //get length of file
cout<<"file length in bytes:"<<length<<endl;
close(handle);

system("pause");
return 0;
}
//用Windows API 中的 GetFileSize()獲得檔案長度
//假設檔案file.txt 在當前目錄下
//file.txt的內容為:123abc
//關於windows API函式情參考部分windows API函式或MSDN
#include <iostream>
#include <windows.h> //for windows api
using namespace std;
int main()
{
//用API函式CreateFile()建立檔案控制代碼
//OPEN_EXISTING 檔案存在則開啟並讀取
//file.txt檔名或路徑
HANDLE fhadle = CreateFile("file.txt", 0,0,0,OPEN_EXISTING, 0,0);
DWORD size = GetFileSize(fhadle,0);
cout<<"size:"<<size<<endl;
return 0;
}
//假設檔案file.txt存在,且在當前目錄下
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
	ifstream in("file.txt");
	in.seekg(0, ios::end); //設定檔案指標到檔案流的尾部
	streampos ps = in.tellg(); //讀取檔案指標的位置
	cout << "File size: " << ps << endl;
	in.close(); //關閉檔案流
	return 0;
}
#include <sys\stat.h>;
#include <string.h>;
#include <stdio.h>;
#include <fcntl.h>;
#include <io.h>;

int main(void)
{
int handle;
char msg[] = "This is a test";
char ch;

/* create a file */
	handle = open("TEST.$$$", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);

	write(handle, msg, strlen(msg));
	lseek(handle, 0L, SEEK_SET);
	do
	{
		read(handle, &ch, 1);
		printf("%c", ch);
	} while (!eof(handle));

	close(handle);
	return 0;
}