Using _sopen()/_sopen_s(), _close(), _chsize()



Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Changing the file size programmatically

To show: Using _sopen()/_sopen_s(), _close(), _chsize()


#include <windows.h>

#include <io.h>

#include <fcntl.h>

#include <sys.h>

#include <share.h>

#include <stdio.h>


int main(void)


/* fhdl is file handle */

int fhdl;

/* the file is already existed or not? */

char fname[20] = "C:\\data.txt";


/* Open a file */

/* The older and unsafe version is _open() */

if((_sopen_s(&fhdl, fname, _O_RDWR | _O_CREAT, _SH_DENYNO, _S_IREAD | _S_IWRITE)) != -1)


printf("%s file length before running the _chsize(): %ld\n", fname, _filelength(fhdl));

/* Change the file size */

printf("\nExecuting _chsize(fhdl, 123456)...\n");

if((_chsize(fhdl, 123456)) == 0)

printf("\n%s file size successfully changed!\n", fname);


printf("\nProblem in changing the %s size! error: %d\n", fname, GetLastError());

/* New size */

printf("\n%s file length after changing the size: %ld\n", fname, _filelength(fhdl));

/* close the file handle */




printf("\n%s cannot be created or opened!\n", fname);


return 0;



Output example:


C:\data.txt file length before running the_chsize(): 123456

Executing _chsize(fhdl, 123456)...

C:\data.txt file size successfully changed!

C:\data.txt file length after changing the size: 123456

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index