Setting File Size

I am writing a program using visual C++ 2010. I would like to ask how do i set text file size to 50000KB, currently the output of test.txt is only 700KB.

const int FILE_SIZE = 50000; //size in KB
double a;
int i;

FILE *pFile = fopen ("test.txt", "w");
for (i = 0; i < FILE_SIZE; i++)
{
a=rand();
fprintf(pFile, "%e\n",a);
}
fclose(pFile);*/

return 0;
Firstly, when working with 'big' numbers u always have to be careful not to go out of bounds which each of the functions you use...Also, if you're trying to open this with a basic text editor since they also have file size limits. (window's notepad is just over 50000 KB)

Note that 'FILE_SIZE' is not necessarily going to equal the size in KB. The size is currently determined by how much you are printing with fprintf. fprintf prints the value of %e (13 characters) + the \n you have for each loop. So that's 14 characters in total for each loop. 1 char = 1 byte, so 14 chars = 14bytes. So, it'd take about 74 loops in your function to reach 1 kilobyte. Therefore, 74 * 50000KB = ~3650000 loops to reach 50K KB.



This should work and get you around 50000KB:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	int oneloop= 14*74;          //for 1 kilobyte
        int filesize = 50000;                      //size in kilobytes
        const  int TOTAL_LOOPS = oneloop * filesize;   
	double a = 0;


	FILE *pFile = fopen ("test.txt", "w");
	for (int i = 0; i < TOTAL_LOOPS; i++)
	{
		a = rand();
		fprintf(pFile, "%e\n",a);		
	}

	fclose(pFile);


return 0;
Last edited on
If you directly use windows API, CreateFile() and SetFilePointer() is all you want. The file is automatically written with 'zeros' by the operating system even if you don't write anything into it.
Topic archived. No new replies allowed.