📝
File I/O

Reading & Writing Files

fprintf, fscanf, fgets, fputs
💡 File se padhna/likhna printf()/scanf() jaisa hi hai, bas ek extra parameter (FILE*) ke saath — ye batata hai ki screen ki jagah KAUNSI file ke saath baat karni hai.

fprintf(fp, format, ...) printf() jaisa hai, output screen par nahi, file mein jaata hai. fscanf(fp, format, ...) scanf() jaisa hai, input keyboard se nahi, file se aata hai. fgets(str, size, fp) ek poori line file se padhta hai (safe, size-limited).

File padhte waqt, end-of-file (EOF) check karna zaroori hai — jab tak file mein data hai tab tak loop chalao, EOF hit hote hi ruko. feof(fp) ya fgets()/fscanf() ka return value (NULL/EOF milna) ye batata hai.

#include <stdio.h>

int main() {
  // Likhna:
  FILE *fp = fopen("data.txt", "w");
  fprintf(fp, "Aarav 85\n");
  fprintf(fp, "Riya 92\n");
  fclose(fp);

  // Padhna:
  fp = fopen("data.txt", "r");
  char name[20];
  int marks;

  while (fscanf(fp, "%s %d", name, &marks) != EOF) {
    printf("%s scored %d\n", name, marks);
  }
  fclose(fp);
  return 0;
}
📝
File se padhna/likhna printf()/scanf() jaisa hi hai, bas ek extra parameter (FILE*) ke saath — ye batata hai ki screen ki jagah KAUNSI file ke saath baat karni hai.
1 / 2
⚡ Quick Recap
  • fprintf/fscanf = printf/scanf jaisa, file ke saath
  • fgets() line-by-line safe reading ke liye
  • EOF check karke loop rokna zaroori hai
On this page (2 subtopics)

fread(ptr, size, count, fp) aur fwrite(ptr, size, count, fp) raw binary data padhte/likhte hain — text formatting ki koi zaroorat nahi (fprintf/fscanf ke ulat). Structs ya arrays ko poora ka poora ek call mein likh sakte ho.

struct Student { char name[20]; int marks; };

// Likhna:
struct Student s1 = {"Aarav", 85};
FILE *fp = fopen("students.dat", "wb");
fwrite(&s1, sizeof(struct Student), 1, fp);
fclose(fp);

// Padhna:
struct Student s2;
fp = fopen("students.dat", "rb");
fread(&s2, sizeof(struct Student), 1, fp);
printf("%s: %d\n", s2.name, s2.marks);
fclose(fp);

Normally files sequentially (shuru se end tak) padhi jaati hain. fseek(fp, offset, origin) se file ke kisi bhi position par "jump" kar sakte ho — random access. ftell(fp) current position batata hai (bytes mein, file ki shuruaat se).

FILE *fp = fopen("data.txt", "r");

fseek(fp, 0, SEEK_END);   // end tak jao
long size = ftell(fp);     // file ki total size mil gayi
printf("File size: %ld bytes\n", size);

fseek(fp, 0, SEEK_SET);   // wapas shuru mein jao
fclose(fp);
💡Tip: fseek(fp, 0, SEEK_END) + ftell(fp) file ka size nikalne ka ek classic C trick hai — bina koi library function ke, sirf file position manipulation se.