您的位置:首页 > 运维架构 > Linux

创建指定大小的文件

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  file report linux