/* * filetest — exercise minimal FILE * stream API (fopen/fclose/fputs/ * fgets/fread/fwrite/fseek/ftell/feof + stdin/stdout/stderr). * * Steps: * 1. fopen("FILE.TXT","w"), fputs+fputc lines, fclose. * 2. fopen("FILE.TXT","r"), fgets each line, fclose. * 3. fopen("r"), fread block, fseek, ftell, feof, fread again. * 4. fputs to stdout (sanity check console pseudo-stream). */ #include #include #include int main(void) { const char *path = "FILE.TXT"; /* ----- 1. Write via fputs + fputc ----- */ { FILE *fp = fopen(path, "w"); if (!fp) { printf("fopen(w) failed: errno=%d (%s)\n", errno, strerror(errno)); return 1; } fputs("Hello from FILE*\n", fp); fputs("Second line via fputs\n", fp); for (int i = '0'; i <= '9'; i++) fputc(i, fp); fputc('\n', fp); if (fclose(fp) != 0) puts("fclose: error"); } /* ----- 2. Read via fgets ----- */ { FILE *fp = fopen(path, "r"); if (!fp) { printf("fopen(r) failed: errno=%d\n", errno); return 1; } char buf[128]; int n = 0; while (fgets(buf, sizeof buf, fp)) { printf(" line %d: %s", ++n, buf); if (buf[strlen(buf)-1] != '\n') putchar('\n'); } printf(" total lines: %d, feof=%d\n", n, feof(fp)); fclose(fp); } /* ----- 3. fread / fseek / ftell ----- */ { FILE *fp = fopen(path, "r"); if (!fp) return 1; char buf[16]; size_t got = fread(buf, 1, 16, fp); printf(" fread(16) -> %u bytes, ftell=%ld\n", (unsigned)got, ftell(fp)); if (fseek(fp, 0L, SEEK_END) == 0) { printf(" file size via fseek(END)+ftell = %ld\n", ftell(fp)); } rewind(fp); printf(" rewind: ftell=%ld, feof=%d\n", ftell(fp), feof(fp)); fclose(fp); } /* ----- 4. Console pseudo-streams ----- */ fputs(" fputs to stdout works\n", stdout); fputs(" fputs to stderr works\n", stderr); fputc('!', stdout); fputc('\n', stdout); puts("filetest done."); return 0; }