File Handling, Command-Line Arguments, and the Preprocessor
Learn how C programs work with files, command-line input, and preprocessing directives for modular and configurable builds.
Inside this chapter
- File Handling Basics
- Reading and Writing
- Command-Line Arguments
- Preprocessor Directives
- Header Guards
- Real-World Usage Snapshot
Series navigation
Study the chapters in order for the clearest path from C basics to advanced memory, systems, debugging, and real-world development practice. Use the navigation at the bottom of each page to move smoothly through the full tutorial.
File Handling Basics
#include <stdio.h>
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello file\n");
fclose(fp);
}
Files are central to logging, configuration, report generation, data persistence, and system utilities. C handles files through standard library functions and file pointers.
Reading and Writing
Functions such as fgetc, fgets, fscanf, fprintf, fread, and fwrite support text and binary file processing. Students should understand the difference between text-mode thinking and raw binary data handling.
Command-Line Arguments
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
return 0;
}
Command-line arguments make C programs flexible and scriptable, especially for tools, automation, and utilities.
Preprocessor Directives
#include <stdio.h>
#define PI 3.14159
#ifdef DEBUG
printf("Debug mode\n");
#endif
The preprocessor is powerful but can be misused. Macros should be kept clear and intentional because debugging macro-heavy code can be difficult.
Header Guards
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int add(int a, int b);
#endif
Header guards prevent multiple inclusion problems and are essential in modular C projects.
Real-World Usage Snapshot
Command-line tools, log processors, build scripts, data converters, and diagnostic utilities rely heavily on file I/O and arguments. The preprocessor, meanwhile, plays a big role in portability, feature toggles, and compilation control in large C codebases.