C

C Fundamentals

18 lessons

Progress0%
1. Introduction to C
1What is C?
2. Variables and Data Types
1Data Types in C
3. Control Flow
ConditionalsLoops
4. Functions
Defining FunctionsRecursion
5. Arrays and Pointers
Arrays and StringsPointers
6. Memory Management
Dynamic MemoryStructs and Files
7. Preprocessor & Macros
Preprocessor DirectivesMacros & Inline Functions
8. Bitwise Operations
Bitwise OperatorsBit Flags & Masking
9. Enums, Unions & typedef
Enums & typedefUnions & Complex Types
10. Multi-file Programs
Header Files & Compilation UnitsLinkage, Storage Classes & Make
All Tutorials
CMemory Management
Lesson 10 of 18 min
Chapter 6 · Lesson 2

Structs and Files

Structs and File I/O in C

struct definition Groups related variables of different types under one name:

c
struct Point { int x; int y; };
struct Point p = {3, 4};

Use typedef to avoid repeating struct:

c
typedef struct { int x; int y; } Point;
Point p = {3, 4};

Struct pointers with -> When you have a pointer to a struct, use -> to access members (equivalent to (*ptr).member):

c
Point *pp = &p;
printf("%d\n", pp->x);

File I/O

  • fopen(path, mode) — opens a file ("r", "w", "a", "rb", etc.)
  • fclose(fp) — closes the file and flushes the buffer
  • fprintf(fp, fmt, …) — writes formatted text
  • fscanf(fp, fmt, …) — reads formatted text
  • fgets(buf, size, fp) — reads a line safely
  • Always check fopen returns non-NULL

Key points:

  • Structs are value types — assignment copies all fields.
  • File handles (FILE*) must be closed to avoid resource leaks.
  • Prefer fgets over fscanf for reading strings to avoid buffer overflows.

Code Examples

typedef struct and pointer accessc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[50];
    int age;
    double gpa;
} Student;

void printStudent(const Student *s) {
    printf("Name: %s, Age: %d, GPA: %.2f\n", s->name, s->age, s->gpa);
}

int main(void) {
    Student s1;
    strncpy(s1.name, "Alice", sizeof(s1.name) - 1);
    s1.name[sizeof(s1.name) - 1] = '\0';
    s1.age = 20;
    s1.gpa = 3.85;

    printStudent(&s1);

    Student *s2 = (Student*) malloc(sizeof(Student));
    strncpy(s2->name, "Bob", sizeof(s2->name) - 1);
    s2->name[sizeof(s2->name) - 1] = '\0';
    s2->age = 22;
    s2->gpa = 3.5;

    printStudent(s2);
    free(s2);
    return 0;
}

The dot operator accesses struct members by value; -> accesses them through a pointer. Both s1 and s2 use the same printStudent function.

File I/O with fprintf and fgetsc
#include <stdio.h>
#include <string.h>

int main(void) {
    // Write to a file
    FILE *fp = fopen("students.txt", "w");
    if (fp == NULL) {
        fprintf(stderr, "Cannot open file\n");
        return 1;
    }
    fprintf(fp, "Alice 20 3.85\n");
    fprintf(fp, "Bob 22 3.50\n");
    fprintf(fp, "Charlie 21 3.70\n");
    fclose(fp);

    // Read back
    fp = fopen("students.txt", "r");
    if (fp == NULL) return 1;

    char name[50];
    int age;
    double gpa;
    while (fscanf(fp, "%s %d %lf", name, &age, &gpa) == 3) {
        printf("%-10s age=%d gpa=%.2f\n", name, age, gpa);
    }
    fclose(fp);
    return 0;
}

fopen returns NULL on failure — always check. fscanf returns the number of items matched; the loop exits when it can no longer match 3 items.

Quick Quiz

1. What is the difference between `.` and `->` for struct member access?

2. What does `fopen` return if it fails to open a file?

Was this lesson helpful?

PreviousNext