Karlo Kraljic Karlo Kraljic - 1 year ago 85
C Question

Optimization of C code- prevent multiple file openings

yyin = fopen("input_file.txt","r");
while ((nread = fread(buf, 1, sizeof buf, yyin)) > 0){
fwrite(buf, 1, nread, stdout);
}
fclose(yyin);
yyin = fopen("input_file.txt","r");
yyparse();
fclose(yyin);


As you see, I open multiple times the same file. First I want to print the output in my cmd/terminal; then I want to start the parser. The problem is obvious: Each opening process costs resources, but the combination of fread and fwrite seems to "clean" my input file so that yyparse does not get any further input and basically stays empty.

Do you have any idea of how to make this more performant or smooth with out 2 file openings?

Answer Source

You can use rewind() to return to the beginning of the file again. See this documentation for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download