Opening file for input and output, through file handle and then close it

 

 

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: Opening file for input and output, file handle and then close it

To show: File handle, open and close

 

 

/* Opening file for input and output, file handle and then close it */

#include <windows.h>

#include <share.h>

#include <fcntl.h>

#include <sys.h>

#include <io.h>

#include <stdio.h>

 

int main(void)

{

int fhand1, fhand2;

/* this file is in the project folder, change accordingly */

char fname1[50] = "cplusrc.cpp";

/* this file is at the location, change accordingly */

char fname2[50] = "E:\\testfolder\\robots.txt";

 

/* fhand1 = _open(fname1, _O_RDONLY); */

_sopen_s(&fhand1, fname1, _O_RDONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE );

 

if(fhand1 == -1)

printf("opening %s failed for input. Error code: %d\n", fname1, GetLastError());

else

{

printf("%s opening succeeded for input\n", fname1);

if(_close(fhand1) == 0)

printf("%s closed successfully!\n", fname1);

else

printf("can't close %s! Error code: %d.\n", fname1, GetLastError());

}

/* fhand2 = _open(fname2, _O_WRONLY | _O_CREAT, _S_IREAD | _S_IWRITE); */

fhand2 = _sopen_s(&fhand2, fname2, _O_WRONLY | _O_CREAT, _SH_DENYNO, _S_IREAD | _S_IWRITE);

if(fhand2 == -1)

printf("%s open failed for output. Error code: %d\n", fname2, GetLastError());

else

{

printf("%s open succeeded for output\n", fname2);

if(_close(fhand2) ==0)

printf("%s closed successfully!\n", fname1);

else

printf("can't close %s! Error code: %d.\n", fname1, GetLastError());

}

return 0;

}

 

Output example:

 

cplusrc.cpp opening succeeded for input

cplusrc.cpp closed successfully!

E:\testfolder\robots.txt open succeeded for output

cplusrc.cpp closed successfully!

Press any key to continue . . .

 

 

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