Ask your own question, for FREE!
Computer Science 10 Online
OpenStudy (anonymous):

What's wrong with my code? # file handling in C It executes, no errors, but the the program hangs. #include #include main() { FILE *fp; char ch; fp=fopen("one.txt","w"); printf("Enter data: "); while((ch=getchar())!='\n') putc(ch,fp); fclose(fp); fp=fopen("one.txt","r"); while((ch=getc(fp))!='\n') printf("%c",ch); fclose(fp); }

OpenStudy (blacksteel):

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.)

OpenStudy (e.mccormick):

Or they could just add the \n after the loop or change the loop to a do while.

OpenStudy (blacksteel):

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.

OpenStudy (e.mccormick):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!