DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Hadoop on AmpereOne Reference Architecture
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Bootstrapping a Java File System
  • Mock the File System

Trending

  • The Architecture and MVC Pattern of an ASP.NET E-Commerce Platform
  • SEO Writing 101: A Simple Guide to Getting Found
  • Performance Testing RAG Applications: Complete Engineering Guide
  • The Middleware Gap in AI Agent Frameworks

How to Create a Sparse File

Let's get your files acting more efficiently.

By 
Francisco Alvarez user avatar
Francisco Alvarez
·
Mar. 19, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.0K Views

Join the DZone community and get the full member experience.

Join For Free

Sparse files are files with “holes”. File holes do not take up any physical space as the file system does not allocate any disk blocks for a hole until data is written into it. Reading a hole returns a null byte.

Virtual machine images are examples of spare files. For instance, when I create a VirtualBox machine and assign it a maximum storage of 100Gb, only the storage corresponding to the actual data in the machine is consumed.

Here’s an example of how to create your own sparse file. The following program writes the string ‘text’ to ‘file’ starting at ‘offset’. If the file does not exist, it is created.

C
 




x
50


 
1
/*
2
    Usage:
3
    write file offset text
4
*/
5

          
6
#include <errno.h>
7
#include <fcntl.h>
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <string.h>
11
#include <sys/types.h>
12
#include <unistd.h>
13

          
14
void errorExit(char *format, const char *text) {
15
    printf(format, errno, text);
16
    perror("");
17
    exit(EXIT_FAILURE);
18
}
19

          
20
int main(int argc, char const *argv[]) {
21
    off_t offset;
22

          
23
    if (argc != 4 || strcmp(argv[1], "--help") == 0)
24
        printf("%s file offset text \n", argv[0]);
25

          
26
    if (*argv[2] == '0') {
27
        offset = 0;
28
    } else if ((offset = atol(argv[2])) == 0) {
29
        printf("cursor_position parameter is %s but must be an integer >= 0",
30
               argv[2]);
31
        exit(EXIT_FAILURE);
32
    }
33

          
34
    int fd = open(argv[1], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
35
    if (fd == -1) {
36
        errorExit("error %d while opening file %s", argv[1]);
37
    }
38

          
39
    if (lseek(fd, offset, SEEK_SET) == -1) {
40
        errorExit("error %d while seeking in file %s", argv[1]);
41
    }
42

          
43
    if (write(fd, argv[3], strlen(argv[3])) != strlen(argv[3])) {
44
        errorExit("error %d while writing file %s", argv[1]);
45
    }
46

          
47
    if (close(fd) == -1) perror("close input");
48

          
49
    exit(EXIT_SUCCESS);
50
}



This other program truncates ‘file’ to size ‘length’. If ‘length’ is greater than the current size of the file, it is extended by padding with a sequence of holes (null bytes).

C
 




x
33



1
/*
2
    Usage:
3
    truncate file length
4
*/
5

          
6
#include <errno.h>
7
#include <stdlib.h>
8
#include <unistd.h>
9
#include <string.h>
10
#include <stdio.h>
11

          
12
void errorExit(char *format, const char *text) {
13
    printf(format, errno, text);
14
    perror("");
15
    exit(EXIT_FAILURE);
16
}
17

          
18
int main(int argc, char *argv[]) {
19
    long length;
20

          
21
    if (argc != 3 || strcmp(argv[1], "--help") == 0)
22
        printf("%s file length\n", argv[0]);
23

          
24
    if((length = atol(argv[2])) == 0) {
25
        printf("'length' parameter is %s but must be an integer > 0", argv[2]);
26
        exit(EXIT_FAILURE);
27
    }
28
    
29
    if (truncate(argv[1], length) == -1)
30
        errorExit("error %d while truncating file %s", argv[1]);
31

          
32
    exit(EXIT_SUCCESS);
33
}



Here’s the above programs in action. Let’s get started by creating a file:

Plain Text
 




x


 
1
% ./write myfile 0 hello
2
% cat myfile             
3
hello
4
% ll myfile   
5
-rw-------  1 xxx  staff  5 14 Mar 20:43 myfile
6
% du -h myfile               
7
4.0K    myfile



‘myfile’ contains 5 bytes. However, as most file systems allocate space in blocks, the size in disk is 1 block of 4096 bytes.

Next, we are going to increase the size of the file by adding holes:

Plain Text
 




x


 
1
% ./truncate myfile 5000       
2
% ll myfile
3
-rw-------  1 xxx  staff  5000 14 Mar 20:49 myfile
4
% du -h myfile
5
4.0K    myfile



The new size is 5000 bytes and yet, the space in disk remains 4096 bytes! Now the final trick, let’s write something in some of the holes without changing the size of the file:

Plain Text
 




x


 
1
% ./write myfile 4500 bye
2
% ll myfile
3
-rw-------  1 xxx  staff  5000 14 Mar 20:54 myfile
4
% du -h myfile
5
8.0K    myfile



The size of the file hasn’t changed but the file system has allocated a new block to account for the data stored in the holes.

File system

Published at DZone with permission of Francisco Alvarez. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Hadoop on AmpereOne Reference Architecture
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Bootstrapping a Java File System
  • Mock the File System

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook