Minimal introduction to NetCDF from Fortran - the simplest starting point.
This is the most basic NetCDF example in Fortran, demonstrating the essential 6-step pattern:
- Create file (nf90_create)
- Define dimensions (nf90_def_dim)
- Define variables (nf90_def_var)
- Add attributes (nf90_put_att)
- Write data (nf90_put_var)
- Close file (nf90_close)
The program creates a tiny 2D array (2x3) with 6 integer values, adds descriptive attributes, writes it to a file, then reopens and reads the data back to verify the round-trip worked.
Learning Objectives:
- Understand the basic NetCDF workflow from Fortran
- Learn how to use the nf90_* API functions
- Master Fortran column-major array ordering
- Implement error handling with check() subroutine
- Verify data integrity
Key Concepts:
- Dimensions: Named axes that define array shapes (X=2, Y=3)
- Variables: Named data arrays with dimensions and types
- Attributes: Metadata describing the file or variables
- Define Mode: Phase where structure is defined (dimensions, variables, attributes)
- Data Mode: Phase where actual data is written/read
- Column-Major: Fortran arrays are stored column-first, opposite of C
Fortran vs C Differences:
- Array Declaration: Fortran data(X, Y) vs C data[X][Y]
- Array Indexing: Fortran 1-based (1 to N) vs C 0-based (0 to N-1)
- API Prefix: Fortran nf90_* vs C nc_*
- Module System: Fortran "use netcdf" vs C "#include <netcdf.h>"
- Error Handling: Fortran check() subroutine vs C ERR() macro
Prerequisites: Basic Fortran 90 programming knowledge
Related Examples:
Compilation:
program f_quickstart
Definition f_quickstart.f90:75
Usage:
Expected Output: Creates f_quickstart.nc containing:
- 2 dimensions: X(2), Y(3)
- 1 variable: data(X, Y) of type int
- 1 global attribute: description = "a quickstart example"
- 1 variable attribute: units = "m/s"
- Data: 6 sequential integers (1, 2, 3, 4, 5, 6)
- Note
- Companion code for "The NetCDF Developer's Handbook: The Authoritative Guide to Writing
High-Performance Programs for Scientific Data Management, Second Edition" (https://www.amazon.com/dp/B0H7Q1Z75L)
- Author
- Edward Hartnett
- Date
- 2026-01-29