Hi I'm trying not to overwrite a file in C using fopen(file, "w");
My question is the file already exists as a 10 MB file but when I used the fopen the file ends up becoming 1KB. I want to write something to the file but I want it to stay the same size as well. How would I accomplish this? I saw that the "a+" appends things to the end of the file but what if I want to write something to the beginning of the file without expanding the size? It's just an empty file
Alternatively, is there a way to create a file in C with a certain size (such as 10MB)?
Yes, it is possible. By opening it with r+
you open it for 'reading and writing' (while w
opens it for writing freshly).
Regarding your other question: Open a file with w
and write 1000 1024 byte blocks to the file like this:
FILE *fp = fopen("file", "wb");
if(fp) {
int i = 0;
char Buf[1024];
for(; i < 1000; ++i)
fwrite(Buf, 1, 1024, fp);
fclose(fp);
}
Just once more the fopen flags for you:
r
-> Opens file for reading. (File remains unchanged)
w
-> Opens file for writing. (File gets erased)
a
-> Opens file for appending. (File remains unchanged, file pointer gets moved to end)
Aside from these three main types, you can add a few more additional options:
b
-> Opens the file as binary, ignoring formatting characters like \n
t
-> Opens the file as text, specifically parsing \n as \r\n under Windows.