Please describe this c language program?

include "stdio.h"

#include "conio.h"

void main()

{

FILE* fp = fopen(__FILE__, "r");

char buf[4096];

clrscr();

printf("\t\t\t\t %s\n\n", __FILE__);

printf("\t\t\t\tTIME: %s\n\n", __TIME__);

printf("\n\n");

while (!feof(fp))

{

fgets(buf, 4096, fp);

printf("%s",buf);

}

fclose(fp);

getch();

}

//Please describe this program step-by-step.Because i want to understand it.

//What is "fgets(buf, 4096, fp);"?

Comments

  • It's a program that prints its own source code...provided that it's run in the directory where the source file is stored.

    __FILE__ is a macro with the name of the source file as a C string literal. It's replaced with something like "printme.c".

    __TIME__ is a macro with the compilation time in string form

    So, the first line opens the source file for "r" reading.

    The second allocates a 4KB buffer to handle reading a line up to 4094 chars. (1 extra char is needed for the \n that ends the line and 1 for the '\0' char that ends the string.)

    The next 4 lines clear the screen and print a heading.

    The while loop repeats until an fgets() call detects end-of-file. It really could be a do {} while(); loop instead.

    The loop body read one line and prints. fgets(buf, size, file) reads at most (size-1) chars from (file) into the char array (buf). It stops after a '\n' newline character has been stored, when end-of-file is seen without a newline, or when (size-1) characters have been stored; whichever comes first. A '\0' string terminator is stored in any case.

    The fclose(fp) call closes the input file.

    The getch() function and "conio.h" header file are not standard C. These are Microsoft C leftovers from MS-DOS days. They are still supported by Visual C++ and by the MinGW port of GNU C for Win32, but have long been deprecated. getch() reads one character from the console keyboard (regardless of whether stdin is redirected) without echo to the console display.

    The only reason to use them is to provide a pause when the program is launched by double-clicking the program icon. In this program, fgets(buf, 4096, stdin); would work just as well without any nonstandard libraries.

    Get used to using fgets() to read whole lines from files. When you see the simpler gets() function later; try to immediately forget it. There is no way to use gets() safely.

  • Java is platform independant. assemble as quickly as and run everywhere. plenty greater reusablility. You dont prefer to could write a similar code lower back and lower back lower back. -is the language of as we communicate and the destiny.

Sign In or Register to comment.