现在的位置: 首页 > 综合 > 正文

创建指定大小的文件

2013年10月11日 ⁄ 综合 ⁄ 共 943字 ⁄ 字号 评论关闭

我们开发的时候创建文件, 一般是创建的时候大小是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;

}

抱歉!评论已关闭.