0

so i'm trying to write this function that gets an argument that tells it whether to display the input to the screen or to redirect it to some file. I'm doing it by redirecting the stdout part. For some reason, the flags in the open() function are not recognized, even though i did #include as required.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h> 
#include <fcntl.h>   
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define TRUE 1
#define FALSE 0
void writer(char* fileName);
void writerEmpty();

void writer(char* fileName)
{
    char buffer[64];
    int size = 64;
    int fd;
    read(0, buffer, size);
    if (!strcmp("std", fileName))
    {
        close(1);
        fd = open(fileName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    }
    write(1, buffer, size);
}

The visual studio doesn't recognize the S_IRUSR and S_IWUSR flags, and when I don't use them at all, open() returns -1 (error). Help? someone? :)

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
themiril
  • 31
  • 3
  • 1
    Switch to a posix compliant compiler like MinGW or find the analogous libs for Windows, AFAIK `unistd.h` and `fnctl.h` are not available in Visual Studio – David Ranieri Apr 14 '18 at 08:33
  • Use cygwin or other POSIX compatible compiler. open is POSIX standard. If you want to create the file in MVS, just use C standard library functions like fopen() – danglingpointer Apr 14 '18 at 08:54
  • 1
    And what value has `errno`? Bad mode should not interfer with opening. Note: closing descriptor 1 and let write into it just after is weird! – Jean-Baptiste Yunès Apr 14 '18 at 09:05
  • @KeineLust Thank you! I have a followup question - my friend did the same code in Visual Studio, and it did work for her. Any suggestions as to why? – themiril Apr 14 '18 at 09:06
  • this might help you https://stackoverflow.com/questions/341817/is-there-a-replacement-for-unistd-h-for-windows-visual-c – Achal Apr 14 '18 at 09:06
  • Did you read [the related documentation](https://learn.microsoft.com/en-gb/cpp/c-runtime-library/reference/open-wopen)? – alk Apr 15 '18 at 09:32

0 Answers0