C Tutorial — Learn C Programming
Key takeaway: This free C tutorial teaches you systems programming from scratch — variables, pointers, arrays, functions, structs, and memory management — with practical code examples you can compile and run.
C is a general-purpose, procedural programming language created in 1972. It is used for operating systems, embedded systems, game engines, and performance-critical applications. This tutorial is for beginners, CS students, and developers who want to understand how computers work at a low level.
Last updated: September 2026
Error Handling in C
C uses return codes and global errno for reporting errors. Robust programs check function results, use perror()/strerror() for diagnostics, and handle invalid states gracefully.
Checking Return Values
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (!fp) {
perror("fopen failed"); // prints: fopen failed: No such file or directory
fprintf(stderr, "errno=%d (%s)\n", errno, strerror(errno));
return 1; // non-zero indicates failure
}
fclose(fp);
return 0;
}Validating Input
#include <stdio.h>
int main() {
int x;
printf("Enter a number: ");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Invalid input.\n");
return 1;
}
printf("You entered: %d\n", x);
return 0;
}Safe File Operations
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "r");
if (!fp) {
perror("fopen");
return 1;
}
char buf[128];
if (!fgets(buf, sizeof(buf), fp)) {
if (feof(fp)) {
fprintf(stderr, "Unexpected EOF.\n");
} else {
perror("fgets");
}
fclose(fp);
return 1;
}
printf("Read: %s\n", buf);
fclose(fp);
return 0;
}Tips
- Check pointers for
NULLbefore dereferencing. - Always validate I/O return values and handle
EOF. - Use consistent error codes and messages; return non-zero on failure.