Created
September 9, 2022 15:32
-
-
Save xantares/23dc23776aee9d867223f376b6fa9809 to your computer and use it in GitHub Desktop.
mingw read EBADF/EACCES issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <errno.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#ifndef _WIN32 | |
#include <unistd.h> | |
#define POSIX(call) call | |
#else | |
#include <io.h> | |
#define POSIX(call) _##call | |
#endif | |
int main() | |
{ | |
// create a file a write into if | |
const char * path = "test-file"; | |
FILE* fp = fopen(path, "w"); | |
fputs("long live the king", fp); | |
fclose(fp); | |
// open file in write-only mode | |
int oflag = POSIX(O_WRONLY); | |
#ifndef _WIN32 | |
int perm = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; | |
#else | |
int perm = _S_IREAD | _S_IWRITE; | |
#endif | |
int fd = POSIX(open(path, oflag, perm)); | |
if (fd < 0) | |
{ | |
printf("ERROR open failed\n"); | |
return 1; | |
} | |
// it should fail to read | |
char buffer = 0; | |
unsigned count = 1; | |
int result = POSIX(read(fd, &buffer, count)); | |
if (result >= 0) | |
{ | |
printf("ERROR read should fail\n"); | |
return 1; | |
} | |
// compare error code mingw->EACCES, linux->EBADF | |
printf("EBADF=%d EACCES=%d\n", EBADF, EACCES); | |
printf("errno=%d\n", errno); | |
if (errno != EBADF) | |
{ | |
printf("errno should be EBADF\n"); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment