Using freopen()

I was going through the facebook puzzles page and 1st puzzle was very simple, just to make you familiarize with the submission process. I made that puzzle and submitted (haven’t got reply yet :(), anyways, after the submission I was going through a page where this problem was solved in variety of languages. I was very proud of my implementation (because I though I have taken care of most of the cases), but there was one very neat and clean implementation available for C. It used freopen(). Damn! I have never used that function, I don’t remember if I have ever heard of it. It is basically a brother of dup() I guess, but closes the first FILE pointer. The usage which I saw was, redirecting a file to stdin. I could never thought of using freopen to redirect any text file to stdin. The nice usage will allow us to use scanf on that file now :) 

So here is the problem definition, and how can one simply implement it using freopen. 

The program will take one input file containing an integer value. It may be preceded with multiple white spaces and it can be ended with multiple white spaces. Your output should iterate from 1 to that number (in file), and print "hop" if the number is multiple of 3 & 5, "hophop" if its multiple of 5, and "hoppit" if multiple of 3. And here is the code using freopen :) 

#include <stdio.h>

int main(int argc, char *argv[])
if (argc != 2) {
printf("Invalid args\n");
printf("Usage: %s <filename>\n", argv[0]);
return -1;
} else {
if (freopen(argv[1], "r", stdin)) {
unsigned long long ull_val = 0, i;
scanf("%llu", &ull_val);
for (i=1; i<=ull_val;i++) {
if (i%3 ==0 & i%5==0)
else if (i%3 == 0)
else if (i%5 == 0)
} else {
printf("Unable to open the file\n");
return -1;

return 0;


3 thoughts on “Using freopen()

  1. Bugs can neither be created nor be removed from software by a developer. It can only be converted from one form to another. The total number of bugs in the software always remains constant!

  2. Newton’s 4th Law !!!
    This seems like the Newton’s Famous 4th law, which is generally found on the walls of the public toilets.
    It states that…
    “Though u shake it as much as u can, but the last drop always falls in the underwear,Mind You…ALWAYS!!!”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s