[20170925]建立檔案分配大小.txt

lfree發表於2017-09-25
[20170925]建立檔案分配大小.txt

--//有時候工作需要建立一個檔案.一般在linux下使用dd.總結一下其他方法:

1.方法1:

$ cat a.c

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/io.h>
#include <stdio.h>
int main()
{
    FILE* file = fopen ("test", "w+");
    fseek (file, 64, SEEK_SET);
    fprintf (file, "x");
    fclose (file);
    return 0;
}

$ gcc a.c
$ ./a.out

$ xxd -c 16 test
0000000: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000040: 78                                       x

--//偏移從0記數,這樣建立的檔案大小是65位元組.

2.方法2:.fallocate

--//實際上linux下有一個命令建立與分配檔案大小.fallocate命令.我僅僅知道centos6.X版本有這個命令.
--//按照man文件的提示:核心版本是2.6.31.

# man fallocate

FALLOCATE(1)                                                      FALLOCATE(1)

NAME
       fallocate - preallocate space to a file.

SYNOPSIS
       fallocate [-n] [-o offset] -l length filename

DESCRIPTION
       fallocate  is  used to preallocate blocks to a file.  For filesystems which support the fallocate system call,
       this is done quickly by allocating blocks and marking them as uninitialized, requiring no IO to the data blocks.
       This is much faster than creating a file by filling it with zeros.

       As of the Linux Kernel v2.6.31, the fallocate system call is supported by the btrfs, ext4, ocfs2, and xfs
       filesystems.

       The exit code returned by fallocate is 0 on success and 1 on failure.

#  fallocate -l 10 a
#  ls -l a
-rw-r--r-- 1 root root 10 2017-09-25 15:23:28 a

3.windows下:

--//windows下:
R:\>fsutil file createnew test.out 64
已建立檔案 R:\test.out

R:\>dir test.out
 驅動器 R 中的卷是 RAMDISK
 卷的序列號是 0122-14E0

 R:\ 的目錄

2017/09/25  15:21                64 test.out
               1 個檔案             64 位元組
               0 個目錄    652,371,968 可用位元組

R:\>d:\tools\Vim\vim74\xxd.exe -c 16 test.out
0000000: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
0000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/267265/viewspace-2145422/,如需轉載,請註明出處,否則將追究法律責任。

相關文章