创建指定大小的文件
2010-12-01 13:44
190 查看
我们开发的时候创建文件, 一般是创建的时候大小是0的, 写入多大就会增加多大, 如果我们需要创建一个指定大小的文件, 有什么办法呢? 最笨的方法就是创建之后写入指定大小的无用数据到文件, 如果文件很大, 那就效率太低了.
1. 使用命令
Window下
fsutil file createnew testfile.txt 1024
Linux下
lmktemp testfile.txt 1024
2. 代码实现(不是写入指定大小的数据那种, 这样子太慢了)
http://bbs.et8.net/bbs/showthread.php?t=424033
/* CHSIZE.C: This program uses _filelength to report the size
* of a file before and after modifying it with _chsize.
*/
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int fh, result;
unsigned int nbytes = BUFSIZ;
/* Open a file */
if((fh = _open("data.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE )) != -1)
{
printf( "File length before: %ld/n", _filelength( fh ) );
if( ( result = _chsize( fh, 1024*1024 * 100) ) == 0 )
printf( "Size successfully changed/n" );
else
printf( "Problem in changing the size/n" );
printf( "File length after: %ld/n", _filelength( fh ) );
_close( fh );
}
return 0;
}
1. 使用命令
Window下
fsutil file createnew testfile.txt 1024
Linux下
lmktemp testfile.txt 1024
2. 代码实现(不是写入指定大小的数据那种, 这样子太慢了)
http://bbs.et8.net/bbs/showthread.php?t=424033
/* CHSIZE.C: This program uses _filelength to report the size
* of a file before and after modifying it with _chsize.
*/
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int fh, result;
unsigned int nbytes = BUFSIZ;
/* Open a file */
if((fh = _open("data.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE )) != -1)
{
printf( "File length before: %ld/n", _filelength( fh ) );
if( ( result = _chsize( fh, 1024*1024 * 100) ) == 0 )
printf( "Size successfully changed/n" );
else
printf( "Problem in changing the size/n" );
printf( "File length after: %ld/n", _filelength( fh ) );
_close( fh );
}
return 0;
}
相关文章推荐
- linux下创建一个指定文件大小,并实现从ext2到ext3的转换
- 用dd创建一个指定大小的空文件
- 创建指定大小的文件
- js动态创建fileupload控件,js判断上传文件的大小,超过指定的大小删除掉
- (25)JAVA.IO--使用Java创建指定大小的空文件
- fopen创建指定大小的文件
- shell 创建多个指定大小的文件,循环删除指定大小文件
- C# 创建指定大小文件 C#读取大文件
- 创建指定大小的文件
- 用dd创建一个指定大小的空文件
- 使用Java创建指定大小的空文件
- 创建一个指定大小格式的文件
- 创建指定大小的空文件
- 利用fsutil命令创建指定大小的测试文件
- Linux 命令行 创建指定大小的文件
- 用CMD创建一个指定大小的新文件
- Shell脚本创建指定大小文件的测试数据
- Linux的dd命令创建指定大小文件(空洞文件)的一种实现可能
- Android创建指定大小、类型的文件
- 用Fsutil创建指定大小的文件