help me to understand for loop in this program (handling flie)

0 sachin singh · June 20, 2015
hi pls help me to understand the working of for loop in file handling program how it is initializing ;condition and incrementing the program..
int main(){
    FILE *inp,*outp;
    char in_name[50],out_name[50],ch;
    printf("enter the name of file you want to backup:");
 for (scanf("%s",in_name);(inp=fopen(in_name,"r"))==NULL;
 printf("can not open %s reenter the file name:\n",in_name);
 printf("enter name for back up copy");
 for (scanf("%s",out_name);
 {printf("can not open %s renter file name:\n",out_name);
 /*make a backup 1 char at a time*/
 for (ch=getc(inp);ch !=EOF;ch=getc(inp))
 printf("copied %s to %s \n",in_name,out_name);
 return 0;


Post a Reply


Oldest  Newest  Rating
0 Jon Z. · June 21, 2015
this is the way I understand it.

the for loop has 3 parts inside the brackets :
for(< 1. this happens before the loop starts> ; < 2. the loop only happens if this is true> ; < 3. this happens after every iteration of the loop>)

for (scanf("%s",in_name); (inp=fopen(in_name,"r"))==NULL; scanf("%s",in_name))
printf("can not open %s reenter the file name:\n",in_name);

so in part 1 it asks the user for the name of the file. 

in part 2 it tries to open the file and there are 2 possibilities: a) the file is opened successfully, in and it does not return NULL, so the condition is false and it never enters the loop and the program continues with the code below the loop, or b) there is an error opening the file and it returns NULL, so the condition is true and the message inside the loop is printed, 

and then part 3 it does the same as part 1, it asks for the name of the file, and then it goes to part 2 again and so on...
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator