Since you want the exact functionality of the _chsize_s routine in C, you could just write a mex file to do this using that function. It was simple enough, so I wrote it below. It has a reasonable amount of input error checking, but I did not include a check for huge requested filesize values. That would be something you might want to add. If you are not familiar with mex files, simply place this file somewhere on your MATLAB path, call it some name like preallocatefile.c, set your default directory to that directory, and then do this at the MATLAB prompt:
mex -setup
(then pick your Microsoft C/C++ compiler)
mex preallocatefile.c
Now you have a function that takes two inputs, filename and filesize, and preallocates the file to that size. e.g., at the MATLAB prompt:
preallocatefile("myfile",1024)
would create a 1K file.
James Tursa
----------------------------------------------------------------
// A MATLAB mex function to preallocate (or reallocate/truncate)
// a file to a requested size.
//
// Inputs:
// 1st input: Char string file name
// 2nd input: Requested file size in bytes (any numeric class)
//
// Outputs:
// (none)
//
// Programmer: James Tursa
#include <stdio.h>
#include <io.h>
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *filename;
__int64 filesize;
FILE *fp;
errno_t errno;
if( nrhs != 2 ) {
mexErrMsgTxt("Need exactly two inputs: filename, size");
}
if( nlhs != 0 ) {
mexErrMsgTxt("There are no outputs allowed");
}
if( !mxIsChar(prhs[0]) ) {
mexErrMsgTxt("1st input must be filename char string");
}
if( !mxIsNumeric(prhs[1]) || mxGetNumberOfElements(prhs[1]) != 1 ) {
mexErrMsgTxt("2nd input must be numeric scalar file size");
}
filename = mxArrayToString(prhs[0]);
filesize = mxGetScalar(prhs[1]);
if( filesize < 0 ) {
mexErrMsgTxt("2nd input must be non-negative");
}
fp = fopen( filename, "w" );
mxFree(filename);
if( fp == NULL ) {
mexErrMsgTxt("Unable to open file");
}
errno = _chsize_s( _fileno(fp), filesize );
fclose(fp);
if( errno != 0 ) {
mexErrMsgTxt("Unable to set size of file");
}
}
Thank you James, you're very kind. I'm going to try and compile your
mex file then.