Skip to main content

I/O functions used with data files

Short answer

fprintf and fscanf perform formatted text I/O on files. fwrite and fread transfer binary blocks of data directly between memory and file, useful for structures. They require a file pointer opened with fopen and closed with fclose.

What are different input/output functions used with data files in C? Explain with syntax and examples. (Explain fscanf, fprintf, fread, fwrite functions.)

Data files are accessed through a file pointer (FILE *fp) opened with fopen(). The main input/output functions (all in <stdio.h>) are:

FunctionPurposeSyntax
fprintfWrite formatted textfprintf(fp, "format", list);
fscanfRead formatted textfscanf(fp, "format", &list);
fputc / fgetcWrite / read one characterfputc(ch, fp); ch = fgetc(fp);
fputs / fgetsWrite / read a stringfputs(str, fp); fgets(str, n, fp);
fwriteWrite blocks (binary)fwrite(ptr, size, count, fp);
freadRead blocks (binary)fread(ptr, size, count, fp);
  • fprintf and fscanf work like printf and scanf, but on a file. fscanf returns the number of items read (or EOF).
  • fwrite and fread copy count blocks of size bytes directly between memory and the file, so a whole structure is stored in one call. Here ptr is the address of the data, for example &s for a structure variable s. They return the number of blocks transferred.
#include <stdio.h>

struct rec {
    char name[20];
    int roll;
};

int main(void)
{
    FILE *fp;
    struct rec s = {"Ram", 7}, t;
    char name[20];
    int roll;

    /* formatted I/O on a text file */
    fp = fopen("text.txt", "w");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fprintf(fp, "%s %d\n", "Sita", 12);
    fclose(fp);

    fp = fopen("text.txt", "r");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fscanf(fp, "%s %d", name, &roll);
    printf("fscanf read: %s %d\n", name, roll);
    fclose(fp);

    /* block I/O on a binary file */
    fp = fopen("rec.dat", "wb");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fwrite(&s, sizeof(s), 1, fp);
    fclose(fp);

    fp = fopen("rec.dat", "rb");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fread(&t, sizeof(t), 1, fp);
    printf("fread read : %s %d\n", t.name, t.roll);
    fclose(fp);
    return 0;
}

Output:

fscanf read: Sita 12
fread read : Ram 7

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →