How do I set the size of a file in c ? Would I do this after I fopen?
问题:
回答1:
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
回答2:
Surprised nobody has said this yet - but the easy answer is ftruncate
, which can be used to increase a file's length as well as decrease it. If increasing the extra file data is set to zero-bytes.
FILE *fp=fopen("myfile", "w");
ftruncate(fileno(fp), 1024*1024);
fclose(fp);
Note that if you have previously written data beyond the length you are truncating to, you will first need to fflush
it (see here: ftruncate on file opened with fopen).
ftruncate
info: http://linux.die.net/man/2/ftruncate.
回答3:
The only way in plain standard C is to write x
bytes to the file after opening it in binary mode, and even then, the standard allows an implementation to append an arbitrary number of null bytes to the end without telling you.
On the other hand, with POSIX, it's easy. Simply call ftruncate(fileno(f), x);
回答4:
Can you clarify your question? Do you mean you're trying to create a new file with a particular size or you have an existing file and you want to truncate it?
Truncating an existing file is easy (in Unix variants, anyway) -- use the truncate() function.
For creating the new file - I'm not sure exactly what you'd be asking. Do you want to create a file that's empty but has a particular size? Why would you need to do that? The sparse file technique that others have described (fseek + fputc) creates a "sparse" file that takes up almost no space on disk, but (if you read it) returns all 0s.
回答5:
There's a bunch of ways to do this:
1 . C/C++ only
You can move the file pointer (using fseek()
) to the size you want, and write anything. This will set the size of the file to the location of the file pointer.
However, this approach only lets you increase the size of a file. It doesn't not let you shrink it.
2 . (Windows)
You can make the file using CreateFile()
, then set the file pointer location and use SetEndOfFile()
to set the actual size.
This method in Windows can also be used to shrink the size of a file.
3 . (Linux)
I'm not sure here, but there's probably something in posix that will do it other than just fseek
+ fwrite
.