Page 1 of 1

Fast I/O Using fread() & fwrite

Posted: Sat May 08, 2010 6:22 pm
by Saswat2603
Hi dear programmers !

I just found in some thread that, faster run-times can be achieved by using fread() and fwrite() and the run-times differed from printf() and scanf() by significant amount.

I searched this forum for a bit of explanation in this regard, but didn't find anything really helpful ..

Can any member share their knowledge about this topic ??

Thanx in advance .. :)

Re: Fast I/O Using fread() & fwrite

Posted: Tue May 25, 2010 3:24 pm
by smithdwsn
Printf() and Scanf() functions are used for print the sentence in console and input any sentence or value in console respectively. While fread() and fwrite() are used for the file. So there is no common action or event between them. They are totally different things.

Re: Fast I/O Using fread() & fwrite

Posted: Sat Jan 15, 2011 6:38 pm
by leonardost
That's not quite true, smithdwsn. You can use stdin and stdout in fread() and fwrite() in place of the file handler, and they'll work like scanf() and printf(), albeit in a lower level. You'll have to do your own parsing and formatting, but the speedup can be substantial. I chopped off almost 0.1s from a problem that took ~0.120s with printf() and scanf(). Of course, these kind of optimizations aren't needed to get a problem to be accepted, but they're nice to know.

These threads are a good reference:
http://online-judge.uva.es/board/viewto ... =14&t=2563
http://acm.uva.es/board/viewtopic.php?t ... ight=fread
http://acm.uva.es/board/viewtopic.php?t ... ight=fread

Re: Fast I/O Using fread() & fwrite

Posted: Sun May 01, 2011 10:30 pm
by iriz7482
I know how to use fread() but I don't know how to parse input efficiently (I use strtok() and atoi() to get input numbers). Would anyone please help me :oops:

Re: Fast I/O Using fread() & fwrite

Posted: Thu Sep 08, 2011 12:30 pm
by Gabrielwer
Hello!!
I am trying to read from a text file and tokenize cell phone spy the input. I was getting a segmentation fault until I realized I forgot to close my ifstream. I added the close call and now it loops infinitely. I'm just trying to learn how to use strtok for now, that is why the code doesn't really look complete.

void loadInstructions(char* fileName)
{
ifstream input;
input.open(fileName);
while(!input.eof());
{
string line;
getline (input,line);
char * lineChar = &line[0];
//instruction cmd; //This will be used later to store instructions from the parse
char * token;
token = strtok (lineChar," ");
// just trying to get the line number for now
int lineNumber = atoi(token);
cout << lineNumber << "\n";
}
input.close();
}

Re: Fast I/O Using fread() & fwrite

Posted: Tue Sep 13, 2011 10:16 am
by cranuterj
(I use strtok() and atoi() to get input numbers)
so what's wrong with using stroke and atoi?