C/C++ 获取文件长度(转)

本文介绍了多种在C/C++中获取文件长度的方法,包括使用`filelength()`、`CreateFile()`、`ifstream`、`CFile::GetLength()`、`stat()`函数等。这些方法适用于不同的场景,如简单的文件读取、Windows API操作和文件权限检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<<"file length in bytes:"< < #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<<"size:"< < #include 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; } (四) 在VC中,CFILE的GetLength()函数可直接得到大小: CFile cf; // Attempt to open thefile for reading. if( !cf.Open( pszFilename, CFile::modeRead ) ) return( FALSE ); // Get the size of the file and store // in a local variable. . DWORD dwSize; dwDibSize = cf.GetLength(); (五) #include ; #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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值