What's wrong with my code? # file handling in C
It executes, no errors, but the the program hangs.
#include
It looks like there's a small bug in your code. When you write data to the file, the while loop writes each character until it encounters a \n (return) character, which it does not print to the file. Your second while loop terminates when it encounters a \n character. Since you're not writing the return character to your file, the second loop never terminates (it keeps calling getc, which returns a special value called EOF once there is no more data to read). You can fix it by either writing the return character to the file or by using a different condition to terminate the second while loop (a return value of EOF from getc, for example, which is how you would normally write a real program like this since a \n isn't necessarily the end of the file.)
Or they could just add the \n after the loop or change the loop to a do while.
A do while loop wouldn't solve the problem. All a do while loop does is run the code in the loop before the while condition is checked - the fact that the loop never terminates would still be true. Manually adding a \n to the file after the first loop would obviously fix it, but it's not very good coding practice for a couple of reasons.
In changing it to a do while you would also edit the condition. ``` do { ch=getchar(); putc(ch,fp); } while(ch!='\n') fclose(fp); ``` Since ch is defined outside the loop, it works.
Join our real-time social learning platform and learn together with your friends!