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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • CubeFS: High-Performance Storage for Cloud-Native Apps
  • Hammerspace Empowers GPU Computing With Enhanced S3 Data Orchestration
  • Block Size and Its Impact on Storage Performance
  • Creating Customized and Bootable Disk Images of Host Systems

Trending

  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Integration Isn’t a Task — It’s an Architectural Discipline

How to Create a Sparse File

Let's get your files acting more efficiently.

By 
Francisco Alvarez user avatar
Francisco Alvarez
DZone Core CORE ·
Mar. 19, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.6K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • CubeFS: High-Performance Storage for Cloud-Native Apps
  • Hammerspace Empowers GPU Computing With Enhanced S3 Data Orchestration
  • Block Size and Its Impact on Storage Performance
  • Creating Customized and Bootable Disk Images of Host Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!