file i/o in a variety of languages

Walter Bright newshound2 at digitalmars.com
Fri Aug 27 11:29:01 PDT 2010


Walter Bright wrote:
> Trass3r wrote:
>>> D doesn't look half bad:
>>
>> Yeah that comment about Go says it all:
>>
>>> It's rather amazing that given 30 years of evolution and language 
>>> design, they've still managed to invent a new language that's as hard 
>>> to write error-checking code in as C. Even Java's less verbose! – DK

And here's the C version. Note the heroic attempt to check for errors, and yet 
how most errors are not checked for:
------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *file;
    char buf[128];

    file = fopen("fileio.txt", "w");
    if (!file)
    {
       fprintf(stderr, "Couldn't open file.\n");
       exit(1);
    }

    fprintf(file, "hello");
    fclose(file);

    file = fopen("fileio.txt", "a");
    if (!file)
    {
       fprintf(stderr, "Couldn't open file.\n");
       exit(1);
    }

    fprintf(file, "\nworld");
    fclose(file);

    file = fopen("fileio.txt", "r");
    if (!file)
    {
       fprintf(stderr, "Couldn't open file.\n");
       exit(1);
    }

    fgets(buf, sizeof(buf), file);
    fgets(buf, sizeof(buf), file);

    fclose(file);

    puts(buf);

    return 0;
}


More information about the Digitalmars-d mailing list