Block 2 · Unit 8File Handling11 min · Section 5 of 8
8.5Formatted Input and Output
Covers IGNOU MCS-201 §8.3.3
When a file holds numbers, names and other values in a fixed layout, it is convenient to read and write them exactly as with scanf and printf. That is what fscanf and fprintf do.
They work exactly like printf and scanf, with a file pointer as the first argument. In fact printf(...) is fprintf(stdout, ...) and scanf(...) is fscanf(stdin, ...).
Function
Returns
fprintf
The number of characters written, or a negative value on error
fscanf
The number of input items successfully assigned, or EOF if the input ends before the first item
The return value of fscanf is the key to reading a file of records: if each record has three fields, keep reading while fscanf returns 3.
Check Your Progress 2, question 1
This exercise writes numbers to two files with fprintf and reads them back with fscanf.
Key takeaways
fprintf(fp, ...) and fscanf(fp, ...) work like printf and scanf on a file.
fprintf returns characters written; fscanf returns items assigned or EOF.
Loop while fscanf returns the number of fields in a record.
Use widths such as %29s to protect arrays.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a program fragment that appends a new client record (account 106, name Priya, balance 2500) to bank.txt in the same format as the existing records.
Show worked answer
FILE *fp = fopen("bank.txt", "a"); if (fp == NULL) { perror("bank.txt"); return 1; } fprintf(fp, "%d %s %.0f\n", 106, "Priya", 2500.0); fclose(fp);. Mode "a" keeps the existing five records and writes the new line at the end; fprintf produces “106 Priya 2500” followed by a newline, which the reading program can process with the same fscanf format.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/file-handling/formatted-input-and-output/ to read this page.