How do I set the size of a file in c ? Would I do this after I fopen?
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.
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 .
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With