bebbo / libnix

libnix (v4): a C link library for AmigaOS/m68k
15 stars 9 forks source link

Fopen mode string anomalies #5

Closed BSzili closed 5 years ago

BSzili commented 5 years ago

I noticed a couple oddities with fopen() compared to other implementations.

  1. "r+" creates an empty file if the file doesn't already exists instead of failing
  2. "wt" doesn't work on already existing files

I created a small test program to reproduce these issues.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void)
{
    FILE *fp;
    struct stat st;
    char *fpath = "testfile.txt";

    // make sure the file doesn't exists
    unlink(fpath);
    if (stat(fpath, &st) != -1)
    {
        printf("couldn't delete %s\n", fpath);
        return 1;
    }

    // 1. r+ shouldn't create a file if it doesn't exists
    fp = fopen(fpath, "r+");
    if (fp)
        fclose(fp);

    fp = fopen(fpath, "r");
    if (fp)
    {
        fclose(fp);
        printf("%s is created after trying to open it for reading and writing\n", fpath);
        return 2;
    }

    fp = fopen(fpath, "w");
    if (fp)
        fclose(fp);
    if (stat(fpath, &st) == -1 || !S_ISREG(st.st_mode))
    {
        printf("couldn't create %s\n", fpath);
        return 3;
    }

    // 2. wt should behave like wt+ if the file already exists
    fp = fopen(fpath, "wt");
    if (!fp)
    {
        printf("couldn't open the existing %s for writing\n", fpath);
        return 4;
    }
    fclose(fp);
    unlink(fpath);

    printf("test success\n");

    return 0;
}
bebbo commented 5 years ago

wt ist not valid: http://www.cplusplus.com/reference/cstdio/fopen/

BSzili commented 5 years ago

Hmm. Maybe it's some POSIX or glibc extension, because it's used in EDuke32, and the test program passes with the Cygwin C library and Linux glibc fine.

BSzili commented 5 years ago

I retested it, and the issue is now gone with 44b3bfe762e3192582d4d42b810f490e8c4c22e8.