Using perror(), strerror_s() and _strerror_s()



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: Displaying error strings

To show: Using perror(), strerror_s() and _strerror_s()





/* Several error message functions - perror(), strerror_s() and _strerror_s() */

#include <windows.h>

#include <fcntl.h>

#include <sys.h>

#include <io.h>

#include <share.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

#define SIZE 100


int main(void)


char fname[20] = "testnofile.txt";

int fhndl;

char buf[SIZE];

char buf1[SIZE];

size_t sizeInBytes = 100;


/* Try to open non-existing file */

_sopen_s(&fhndl, fname, _O_RDONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE );


if(fhndl == -1)


/* Using the possible ways to create error message */

perror("\nUsing perror()");

/* printf("Using strerror(): %s\n", strerror(errno)); */

strerror_s(buf, SIZE, errno);

printf("\nUsing strerror(): %s\n", buf);

/* printf(_strerror("_strerror()")); */

_strerror_s(buf1, sizeInBytes, "_strerror()");

printf("\nUsing ");



printf("\nThere is some error opening %s file. Error code: %d.\n", fname, GetLastError());




printf("Open %s for reading succeeded!\n", fname);



return 0;



Output example:


Using perror(): No such file or directory

Using strerror(): No such file or directory

Using _strerror(): No such file or directory

There is some error opening testnofile.txt file. Error code: 2.

Press any key to continue . . .



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