C/C++ 擷取檔案長度

來源:互聯網
上載者:User
C/C++ 擷取檔案長度(轉)
(一)

對檔案操作時有時獲得檔案的大小時必要的.下面是獲得其大小小的較簡單方法.
#include //C 語言標頭檔
#include //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
#include //for windows api
using namespace std;
int main()
{
//用API函數CreateFile()建立檔案控制代碼
HANDLE fhadle = CreateFile("file.txt", //檔案名稱或路徑
0,
0,
0,
OPEN_EXISTING, //檔案存在則開啟並讀取
0,
0);
DWORD size = GetFileSize(fhadle,0);
cout
#include
using namespace std;
int main(int argc, char* argv[])
{
ifstream in("file.txt");
in.seekg(0, ios::end); //設定檔案指標到檔案流的尾部
streampos ps = in.tellg(); //讀取檔案指標的位置
cout ;
#include ;

long
get_filesize(char *filename)
{
struct stat f_stat;
if (stat(filename, &f_stat) == -1) {
return -1;
}
return (long)f_stat.st_size;
}
(六)
int main(void)
{
struct stat statbuf;
FILE *stream;

/* open a file for update */
if ((stream = fopen(FILENAME, "w+")) == NULL)
{
fprintf(stderr, "Cannot open output file./n");
return(1);
}

/* get information about the file */
stat(FILENAME, &statbuf);

fclose(stream);

/* display the information returned */
if (statbuf.st_mode & S_IFCHR)
printf("Handle refers to a device./n");
if (statbuf.st_mode & S_IFREG)
printf("Handle refers to an ordinary file./n");
if (statbuf.st_mode & S_IREAD)
printf("User has read permission on file./n");
if (statbuf.st_mode & S_IWRITE)
printf("User has write permission on file./n");

printf("Drive letter of file: %c/n", 'A'+statbuf.st_dev);
printf("Size of file in bytes: %ld/n", statbuf.st_size);
printf("Time file last opened: %s/n", ctime(&statbuf.st_ctime));

return 0;
}
(七)
#include ;
#include ;
#include ;
#include ;
#include ;

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 some data to the file */
write(handle, msg, strlen(msg));

/* seek to the beginning of the file */
lseek(handle, 0L, SEEK_SET);

/* reads chars from the file until we hit EOF */

do
{
read(handle, &ch, 1);
printf("%c", ch);
} while (!eof(handle));

close(handle);
return 0;
}
來自: http://hi.baidu.com/ignorer/blog/item/274276091ab8eea32fddd42c.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.