C File Input/output - Example

Example

The following C program opens a binary file called myfile, reads five bytes from it, and then closes the file.

#include #include int main(void) { char buffer = {0}; /* initialized to zeroes */ int i, rc; FILE *fp = fopen("myfile", "rb"); if (fp == NULL) { perror("Failed to open file \"myfile\""); return EXIT_FAILURE; } for (i = 0; (rc = getc(fp)) != EOF && i < 5; buffer = rc) { } fclose(fp); if (i == 5) { puts("The bytes read were..."); printf("%x %x %x %x %x\n", buffer, buffer, buffer, buffer, buffer); } else fputs("An error occurred while reading the file.\n", stderr); return EXIT_SUCCESS; }

Read more about this topic:  C File Input/output

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)