I am about to do some data processing in C, and the processing part is working logically, but I am having a strange file problem. I conveniently have 32-bits of numbers to consider, so I need a file of 32-bits of 0s, and then I will change the 0 to 1 if something exists in a finite field.
My question is: What is the best way to make a file with all "0s" in C?
What I am currently doing, seems to make sense but is not working. I currently am doing the following, and it doesn't stop at the 2.4GiB mark. I have no idea what's wrong or if there's a better way.
#include <stdlib.h>
#include <stdio.h>
typedef uint8_t u8;
typedef uint32_t u32;
int main (int argc, char **argv) {
u32 l_counter32 = 0;
u8 l_ubyte = 0;
FILE *f_data;
f_data = fopen("file.data", "wb+");
if (f_data == NULL) {
printf("file error\n");
return(0);
}
for (l_counter32 = 0; l_counter32 <= 0xfffffffe; l_counter32++) {
fwrite(&l_ubyte, sizeof(l_ubyte), 1, f_data);
}
fwrite(&l_ubyte, sizeof(l_ubyte), 1, f_data); //final byte at 0xffffffff
fclose(f_data);
}
I increment my counter in the loop to be 0xFFFFFFFe, so that it doesn't wrap around and run forever.. I haven't waited for it to stop actually, I just keep checking on the disk via ls -alF and when it's larger than 2.4GiB, I stop it. I checked sizeof(l_ubyte), and it is indeed 8-bits.
I feel that I must be missing some mundane detail.
The faster way to create initalize a file with zeroes (alias \0 null bytes) is using truncate()/ftruncate()
. See man page here
You are counting up to 0xffffffff
, which is equal to 4,294,967,295. You want to count up to 0x80000000
for exactly 2 GB of data.
User contributions licensed under CC BY-SA 3.0