Why am I getting errno EINVAL (constant parameters) but only when the file is empty

I am using _fsopen(path, "r+", _SH_DENYRW)

to open the file in C. Any option to protect (_SH _...) causes the same problem.

When opening an empty file, it is errno

set to 22 ( EINVAL

), not so when the file is not empty - then everything is fine. What can I do?

+1


a source to share


1 answer


The documentation implies that EINVAL will result if one of the parameters was invalid. Since it "r+"

must be a valid pointer, and assuming it was compiled at all, it _SH_DENYRW

must be a valid flag, the only remaining question is whether your variable is path

not NULL, points to memory that exists and can be read, and contains a valid pathname.

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." Which means it _fsopen()

succeeded. Several other cases:

Read-only file:

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


No file:

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

Device file:

C:> fsopen NUL:
Open ok.

Zero length file:

C:> fsopen zero.txt
Open ok.
+2


a source







All Articles