I was attempting a problem regarding pointers from a book called problem solving and program design in C. we were formally introduced to functions fscanf()
and fprintf()
where they accept both input file and output file pointers respectively as the first argument of the function. our task is to read from an input file, extract the count for the numbers encoded in floats that are present in the input file and write each number separated by a newline character to an output file and write the number of count underneath the final number that has been written to the output file. the pseudocode for the algorithm read:
main() { double num = 0; int count = 0; input_status = fscanf(inp, "%lf", &num); while (input_status != -1){ fprintf(outp, "%.2f\n", num); count++ input_status = fscanf(inp, "%lf", &num); } // write to the output file the count fprintf(outp, "%d\n", count) close(inp & outp); return (0); }
In the context of this particular algorithm, the follow up question asked: "why can't we write the count as the first item of the output file in this case".
well I answered: the loop basically checks whether we have reached an end of file or not - once the end of file is reached, the pointer variable basically points to the end of the file. Now unless we explicitly defined two for loops - one to count for the number of elements that are present in the input file (our count variable) and the other to write to the output file all the numbers that are present in the input file, we cannot do this as opposed to outputting the elements followed by the number of elements at the end of the file.
I want to know if my answer is valid or not.