Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create file of "x" size?

Tags:

c

file-io

How do I set the size of a file in c ? Would I do this after I fopen?

like image 959
Questioneer Avatar asked Oct 15 '11 00:10

Questioneer


People also ask

How create 10 MB file in Linux?

How To Create A File In Specific Size In Linux Using xfs_mkfile Command? xfs_mkfile creates one or more files. The file is padded with zeroes by default. The default size is in bytes, but it can be flagged as kilobytes, blocks, megabytes, or gigabytes with the k, b, m or g suffixes, respectively.

How do I create a specific file size in Linux?

Create files of a certain size using fallocate command The another command to create a particular size file is fallocate . Please note that you can only specify file sizes in bytes using fallocate command. To calculate the size for a specific file, for example 5MB , you need to do - 510241024=5242880 .

How do you find the file size of a file?

Right-click the file and click Properties. The image below shows that you can determine the size of the file or files you have highlighted from in the file properties window. In this example, the chrome. jpg file is 18.5 KB (19,032 bytes), and that the size on disk is 20.0 KB (20,480 bytes).

How can I get file size in C?

The idea is to use fseek() in C and ftell in C. Using fseek(), we move file pointer to end, then using ftell(), we find its position which is actually size in bytes.


1 Answers

Yes you would do it after fopen - you can create what is know as a sparse file

#include <stdio.h>
int main(void) {
        int X = 1024 * 1024 - 1;
        FILE *fp = fopen("myfile", "w");
        fseek(fp, X , SEEK_SET);
        fputc('\0', fp);
        fclose(fp);
}

That should create you a file for X Byte for whatever you need, in this case it's 1MiB

like image 107
Adrian Cornish Avatar answered Oct 14 '22 01:10

Adrian Cornish