tags:

views:

219

answers:

1

I use _fsopen(path, "r+", _SH_DENYRW) for opening a file in C any parameter for protection (_SH_...) cause the same issue.

When opening an empty file, errno is set to 22 (EINVAL), not so when the file isn't empty - then all is OK. What can I do?

+1  A: 

The documentation implies that EINVAL would the result if one of the parameters were invalid. Since "r+" has to be a valid pointer, and assuming it compiled at all _SH_DENYRW has to be a valid flag, the only remaining question is whether your variable path is not NULL, points to memory that exists and can be read, and contains a valid path name.

I just tried the following:

#include <stdio.h>
#include <share.h>

int main(int argc, char **argv)
{
    FILE *f;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }
    f = _fsopen(argv[1], "r+", _SH_DENYRW);
    if (f) {
        printf("Open ok.\n");
        fclose(f);
    } else {
        perror(argv[1]);
    }
    return 0;
}

On files that exist and can be written, regardless of their size, it prints "Open ok.", meaning that _fsopen() succeeded. A couple of other cases:

A read-only file:

C:>fsopen ro.txt
ro.txt: Permission denied

No file:

C:>fsopen nosuchfile
nosuchfile: No such file or directory

A device file:

C:>fsopen NUL:
Open ok.

A zero-length file:

C:>fsopen zero.txt
Open ok.
RBerteig