Transition from C++ to C. Covers scanf/printf, string handling with fgets, file I/O using fopen/fclose, structs, complex format specifiers, functions with pointer parameters, and dynamic 2D allocation.
scanfprintffopenstructspointers
1
Hello, printf
The first C program: #include <stdio.h>, int main(void), and printf with \n instead of cout and endl — plus the escape sequences \t, \" and \\.
00a-hello-printf.c28 lines
/* * 00a-hello-printf.c — Your first C program: printf instead of cout * * Key concepts: #include <stdio.h>, int main(void), printf, \n and other escape sequences * Compile: gcc -o hello 00a-hello-printf.c * Run: ./hello * * C++: std::cout << "Hello" << std::endl; * C: printf("Hello\n"); */#include <stdio.h> // printf and scanf live here (C++ used <iostream>)int main(void) // (void) = "takes no arguments" — in C, () means "unspecified"{ printf("Hello from C!\n"); // \n ends the line — there is no endl printf("No newline here... "); printf("so this continues the same line.\n"); printf("Escape sequences:\n"); printf(" \\n new line\n"); printf(" \\t tab:\t[after a tab]\n"); printf(" \\\" a quote: \"quoted\"\n"); printf(" \\\\ a backslash: \\\n"); return 0; // 0 = success; the shell sees it as the exit status ($?)}
Editing — changes sent to terminal on Run
$ gcc -o hello 00a-hello-printf.c
$ ./hello
Expected Outputclick Run to execute live
Hello from C!
No newline here... so this continues the same line.
Escape sequences:
\n new line
\t tab: [after a tab]
\" a quote: "quoted"
\\ a backslash: \
2
printf Format Specifiers
One specifier per type — %d, %f, %.2f, %e, %c, %s, %x and %% — and how several arguments are matched to the format left to right.
00b-printf-specifiers.c35 lines
/* * 00b-printf-specifiers.c — printf format specifiers: one per type * * Key concepts: %d %f %c %s %x %e %%, matching each specifier to an argument * Compile: gcc -o specifiers 00b-printf-specifiers.c * Run: ./specifiers * * printf("format", arg1, arg2, ...): every % in the format consumes the next argument, * in order. The specifier MUST match the argument's type — the compiler only warns. */#include <stdio.h>int main(void){ int age = 21; double pi = 3.14159265; char grade = 'A'; char name[] = "Dana"; // a string is an array of chars ending with '\0' printf("%%d int: %d\n", age); printf("%%f double: %f\n", pi); // 6 digits after the point by default printf("%%.2f 2 digits: %.2f\n", pi); printf("%%e scientific: %e\n", pi); printf("%%c char: %c\n", grade); printf("%%s string: %s\n", name); printf("%%x hex: %x\n", 255); printf("%%%% a percent sign: 100%%\n"); // Several values in one call — matched left to right printf("%s is %d years old and got %c (pi = %.3f)\n", name, age, grade, pi); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o specifiers 00b-printf-specifiers.c
$ ./specifiers
Expected Outputclick Run to execute live
%d int: 21
%f double: 3.141593
%.2f 2 digits: 3.14
%e scientific: 3.141593e+00
%c char: A
%s string: Dana
%x hex: ff
%% a percent sign: 100%
Dana is 21 years old and got A (pi = 3.142)
3
Width, Alignment and Padding
Field widths in printf: %5d, %-5d, %05d and %8.2f, used to print a neatly aligned table.
00c-printf-width.c31 lines
/* * 00c-printf-width.c — Width, alignment and padding: printing tables * * Key concepts: %5d (right-aligned), %-10s (left-aligned), %05d (zero padding), %8.2f * Compile: gcc -o width 00c-printf-width.c * Run: ./width * * The number between % and the letter is the MINIMUM width of the field. */#include <stdio.h>int main(void){ printf("[%d] no width\n", 42); printf("[%5d] width 5, right-aligned\n", 42); printf("[%-5d] width 5, left-aligned\n", 42); printf("[%05d] width 5, zero-padded\n", 42); printf("[%8.2f] width 8, 2 decimals\n", 3.14159); printf("[%-8s] string, left-aligned\n", "C"); printf("[%8s] string, right-aligned\n", "C"); // A small table: same widths on every row keep the columns straight printf("\n%-10s %6s %8s\n", "Name", "Grade", "Average"); printf("%-10s %6d %8.1f\n", "Dana", 95, 91.25); printf("%-10s %6d %8.1f\n", "Avi", 78, 80.5); printf("%-10s %6d %8.1f\n", "Noa", 100, 97.75); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o width 00c-printf-width.c
$ ./width
Expected Outputclick Run to execute live
[42] no width
[ 42] width 5, right-aligned
[42 ] width 5, left-aligned
[00042] width 5, zero-padded
[ 3.14] width 8, 2 decimals
[C ] string, left-aligned
[ C] string, right-aligned
Name Grade Average
Dana 95 91.2
Avi 78 80.5
Noa 100 97.8
4
Reading a Number with scanf
scanf("%d", &n) instead of cin >> n: why the & is needed, and checking scanf's return value to catch input that is not a number.
00d-scanf-one-int.c29 lines
/* * 00d-scanf-one-int.c — Reading one number with scanf (instead of cin >>) * * Key concepts: scanf("%d", &n), why the & is needed, scanf's return value * Compile: gcc -o read_int 00d-scanf-one-int.c * Run: ./read_int (type a number and press Enter — then try typing "abc") * * C++: std::cin >> n; * C: scanf("%d", &n); — scanf needs the ADDRESS of n (&n) so it can write into it. * Forgetting the & is the classic first C bug: scanf writes to a random address. */#include <stdio.h>int main(void){ int n = 0; printf("Enter a whole number: "); int matched = scanf("%d", &n); // returns how many values it managed to read if (matched == 1) printf("You entered %d, twice that is %d\n", n, n * 2); else printf("That was not a number (scanf returned %d)\n", matched); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o read_int 00d-scanf-one-int.c
$ ./read_int
Expected Outputclick Run to execute live
42
Enter a whole number: You entered 42, twice that is 84
Asks for input — sample input is one click away
5
Several Values in One scanf
Reading an int and a double together with "%d %lf" (%lf for double), and a literal comma in the format with "%d,%d".
00e-scanf-many.c35 lines
/* * 00e-scanf-many.c — Reading several values, of different types, in one scanf * * Key concepts: %d %lf in one format, %lf for double (printf uses %f), literal characters in the format * Compile: gcc -o read_many 00e-scanf-many.c * Run: ./read_many (try: 7 2.5 then 3,4) * * Spaces and Enter between numbers are skipped automatically. * Any other character in the format (like the comma in "%d,%d") must appear in the input. */#include <stdio.h>int main(void){ int count; double price; printf("How many items and the price of one (e.g. 7 2.5): "); if (scanf("%d %lf", &count, &price) != 2) { // %lf reads a double; %f would read a float printf("Expected a whole number and a decimal number.\n"); return 1; } printf("%d x %.2f = %.2f\n", count, price, count * price); int x, y; printf("A point as x,y (e.g. 3,4): "); if (scanf("%d,%d", &x, &y) == 2) // the comma must be typed too printf("Point (%d, %d)\n", x, y); else printf("Could not read x,y — did you type the comma?\n"); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o read_many 00e-scanf-many.c
$ ./read_many
Expected Outputclick Run to execute live
7 2.5
3,4
How many items and the price of one (e.g. 7 2.5): 7 x 2.50 = 17.50
A point as x,y (e.g. 3,4): Point (3, 4)
Asks for input — sample input is one click away
6
Strings, Characters and the Leftover Newline
%s stops at the first space and needs no &, %19s limits the length, and " %c" with a cleared input line avoids the classic leftover-newline bug.
00f-scanf-strings-chars.c32 lines
/* * 00f-scanf-strings-chars.c — Strings and single characters with scanf, and the leftover newline * * Key concepts: %s stops at whitespace, no & for arrays, %19s limits the length, " %c" skips the '\n' * Compile: gcc -o read_text 00f-scanf-strings-chars.c * Run: ./read_text (try typing two words: Yaniv Gabay) */#include <stdio.h>int main(void){ char first[20]; char initial; printf("Your full name: "); scanf("%19s", first); // no &: the array name is already an address; 19 + '\0' = 20 printf("%%s read only \"%s\" — it stops at the first space\n", first); // The rest of the line (" Gabay" + Enter) is still waiting in the input buffer: // the next scanf would read 'G' from it instead of waiting for you. Throw it away first. int c; while ((c = getchar()) != '\n' && c != EOF) ; printf("Your grade letter: "); scanf(" %c", &initial); // the space before %c skips any spaces/Enter left over — a good habit printf("Grade '%c' — its ASCII code is %d\n", initial, initial); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o read_text 00f-scanf-strings-chars.c
$ ./read_text
Expected Outputclick Run to execute live
Yaniv Gabay
A
Your full name: %s read only "Yaniv" — it stops at the first space
Your grade letter: Grade 'A' — its ASCII code is 65
Asks for input — sample input is one click away
7
Basic Input & Output
Side-by-side comparison of C scanf/printf versus C++ cin/cout, showing equivalent I/O operations.
01-basic-input-output.c178 lines
/* * 01-basic-input-output.c — Basic I/O — scanf/printf vs C++ cin/cout * * Key concepts: scanf, printf, format specifiers * Compile: gcc -o prog 01-basic-input-output.c * Run: ./prog *///differences between c and cpp/*#include <iostream>int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Basic I/O\n"); printf("══════════════════════════════════════\n\n"); int number; std::cout << "Enter a number: "; std::cin >> number; std::cout << "You entered: " << number << std::endl; return 0;}*/// to write the same program in c://https://en.cppreference.com/w/c/io //IMPORTANT#include <stdio.h>//https://en.cppreference.com/w/c/io/fscanfvoid print_test(char* input,char* output,char* prase_type){ printf(" Input: \"%s\"\n", input); printf(" Result: \"%s\" (%s)\n\n", output, prase_type);}int main(){ printf("\n"); // --- Section 1: Interactive input --- printf("--- Section 1: Reading input with scanf ---\n\n"); int number; printf(" Enter a number: "); fflush(stdout); scanf("%d", &number); // scanf() reads formatted input from the standard input (stdin) // sscanf() reads formatted input from a string // there is also fscanf() function in c // check out more in the link printf(" You entered: %d\n\n", number); //https://en.cppreference.com/w/c/io/fscanf /* conversion specifiers %d: a decimal integer. %f: a floating-point value %c: a character [set]: a string of characters that match the set - for example %9[0-9] is a string of at most 9 decimal digits - google scansets in c for more info %s: a string of characters that aren't whitespace %9s: a string of at most 9 non-whitespace characters %2d: two-digit integer - for example 99 %*d: an integer which isn't stored anywhere ' ': all consecutive whitespace %3[0-9]: a string of at most 3 decimal digits %i: a integer (can be octa, hexa or dec) */ // --- Section 2: Parsing with sscanf --- printf("--- Section 2: Parsing strings with sscanf ---\n\n"); printf(" %-12s | %-20s | %-10s | %s\n", "Format", "Input", "Result", "Notes"); printf(" ------------ | -------------------- | ---------- | -----\n"); char input1[] = "42"; int num; sscanf(input1, "%d", &num); printf(" %-12s | %-20s | %-10d | integer\n", "%d", input1, num); char input2[] = "3.14"; float fnum; sscanf(input2, "%f", &fnum); printf(" %-12s | %-20s | %-10.2f | float\n", "%f", input2, fnum); char input4[] = "99"; int twoDigitNum; sscanf(input4, "%2d", &twoDigitNum); printf(" %-12s | %-20s | %-10d | 2-digit only\n", "%2d", input4, twoDigitNum); char input5[] = "1.23E4"; float sciNum; sscanf(input5, "%f", &sciNum); printf(" %-12s | %-20s | %-10.0f | scientific\n", "%f (sci)", input5, sciNum); printf("\n"); // --- Section 3: String parsing with %%s and width --- printf("--- Section 3: String parsing with %%s (max 9 chars) ---\n\n"); char input3[] = " HelloWorld"; char input3_a[] = "Hello World"; char input3_b[] = " a b c d e d g"; char str2[10]; char str2_a[10]; char str2_b[10]; sscanf(input3, "%9s", str2); printf(" Input: \" HelloWorld\" -> %%9s -> \"%s\"\n", str2); sscanf(input3_a, "%9s", str2_a); printf(" Input: \"Hello World\" -> %%9s -> \"%s\" (stops at whitespace)\n", str2_a); sscanf(input3_b, "%9s", str2_b); printf(" Input: \" a b c d e...\" -> %%9s -> \"%s\" (skips leading spaces)\n", str2_b); printf("\n"); // --- Section 4: Parsing multiple fields at once --- printf("--- Section 4: Parsing multiple fields at once ---\n\n"); int i, j; float x, y; char str1[10]; char input[] = "25 54.32E-1 Thompson 56789"; int ret = sscanf(input, "%d%f%9s%2d%f%*d", &i, &x, str1, &j, &y); printf(" Input: \"%s\"\n", input); printf(" Format: \"%%d%%f%%9s%%2d%%f%%*d\"\n\n"); printf(" Fields converted: %d\n", ret); printf(" %%d -> i = %d\n", i); printf(" %%f -> x = %.3f\n", x); printf(" %%9s -> str1 = \"%s\"\n", str1); printf(" %%2d -> j = %d (only first 2 digits of 56789)\n", j); printf(" %%f -> y = %.0f (remaining digits)\n", y); printf(" %%*d -> skipped (the * means: read but discard)\n"); printf("\n"); // --- Section 5: Scansets [set] --- printf("--- Section 5: Scansets — character class matching ---\n\n"); char input7[] = "123456"; char str4[4]; sscanf(input7, "%3[0-9]", str4); printf(" %%3[0-9] : digits only, max 3\n"); print_test(input7, str4, "first 3 digits"); //this will stop at first non digit character char input6_a[] = "12a3456"; char str3_a[4]; sscanf(input6_a, "%3[0-9]", str3_a); printf(" %%3[0-9] : stops at non-digit\n"); print_test(input6_a, str3_a, "stopped at 'a'"); char input8[] = "123456X789"; char str5[10]; sscanf(input8, "%9[^X]", str5); printf(" %%9[^X] : everything except 'X'\n"); print_test(input8, str5, "stopped at 'X'"); char input9[] = "abcd4"; char str6[10]; sscanf(input9, "%[a-zA-Z]", str6); printf(" %%[a-zA-Z]: alphabetic only\n"); print_test(input9, str6, "stopped at '4'"); char input10[] = "Hello World\n abcde"; char str7[25]; sscanf(input10, "%[^\n]", str7); printf(" %%[^\\n] : read until newline\n"); print_test(input10, str7, "stopped at \\n"); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o basic_io 01-basic-input-output.c
$ ./basic_io
Expected Outputclick Run to execute live
--- Section 1: Reading input with scanf ---
Enter a number: 42
You entered: 42
--- Section 2: Parsing strings with sscanf ---
Format | Input | Result | Notes
------------ | -------------------- | ---------- | -----
%d | 42 | 42 | integer
%f | 3.14 | 3.14 | float
%2d | 99 | 99 | 2-digit only
%f (sci) | 1.23E4 | 12300 | scientific
--- Section 3: String parsing with %s (max 9 chars) ---
Input: " HelloWorld" -> %9s -> "HelloWorl"
Input: "Hello World" -> %9s -> "Hello" (stops at whitespace)
Input: " a b c d e..." -> %9s -> "a" (skips leading spaces)
--- Section 4: Parsing multiple fields at once ---
Input: "25 54.32E-1 Thompson 56789"
Format: "%d%f%9s%2d%f%*d"
Fields converted: 5
%d -> i = 25
%f -> x = 5.432
%9s -> str1 = "Thompson"
%2d -> j = 56 (only first 2 digits of 56789)
%f -> y = 789 (remaining digits)
%*d -> skipped (the * means: read but discard)
--- Section 5: Scansets — character class matching ---
%3[0-9] : digits only, max 3
Input: "123456"
Result: "123" (first 3 digits)
%3[0-9] : stops at non-digit
Input: "12a3456"
Result: "12" (stopped at 'a')
%9[^X] : everything except 'X'
Input: "123456X789"
Result: "123456" (stopped at 'X')
%[a-zA-Z]: alphabetic only
Input: "abcd4"
Result: "abcd" (stopped at '4')
%[^\n] : read until newline
Input: "Hello World
abcde"
Result: "Hello World" (stopped at \n)
Asks for input — sample input is one click away
8
More Basic I/O
Extended I/O examples covering multiple data types and format specifiers.
02-more-basic-input-output.c59 lines
/* * 02-more-basic-input-output.c — More I/O — multiple data types and format specifiers * * Key concepts: scanf, printf, data types * Compile: gcc -o prog 02-more-basic-input-output.c * Run: ./prog */// to write the same program in c://https://en.cppreference.com/w/c/io //IMPORTANT#include <stdio.h>//https://en.cppreference.com/w/c/io/fscanfint main(){ printf("\n"); printf("══════════════════════════════════════\n"); printf(" More I/O\n"); printf("══════════════════════════════════════\n\n"); // there are MANY variant of scanf and printf // scanf() and printf() are the most basic ones //basic scanf: printf("\n"); // --- Section 1: Basic scanf --- printf("--- Section 1: Basic scanf (reading from keyboard) ---\n\n"); int number; printf(" Enter a number: "); fflush(stdout); scanf("%d", &number); printf(" You entered: %d\n\n", number); // --- Section 2: sscanf (parsing from a string) --- printf("--- Section 2: sscanf (reading from a string) ---\n\n"); //its very helpful, when you have a string and you need to // extract some data from it char data[] = "123 456"; int a, b; // (parameters: string, format, variables) sscanf(data, "%d %d", &a, &b); printf(" Input string: \"%s\"\n", data); printf(" sscanf(data, \"%%d %%d\", &a, &b)\n"); printf(" Result: a = %d, b = %d\n\n", a, b); // --- Section 3: snprintf (safe formatted printing to a string) --- printf("--- Section 3: snprintf (print to string, not screen) ---\n\n"); // another usefull in my opinion is snprintf // which instead of printing to std output, it prints to a string // which buffer overflow protection char buffer[10]; // Small buffer to demonstrate overflow protection int length = snprintf(buffer, sizeof(buffer), "Hello, %s!", "World"); printf(" Buffer size: %zu bytes\n", sizeof(buffer)); printf(" snprintf(buffer, %zu, \"Hello, %%s!\", \"World\")\n", sizeof(buffer)); printf(" Result: \"%s\"\n", buffer); printf(" Wanted length: %d (truncated because buffer is only %zu bytes)\n\n", length, sizeof(buffer)); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o more_io 02-more-basic-input-output.c
$ ./more_io
Expected Outputclick Run to execute live
══════════════════════════════════════
More I/O
══════════════════════════════════════
--- Section 1: Basic scanf (reading from keyboard) ---
Enter a number: 7
You entered: 7
--- Section 2: sscanf (reading from a string) ---
Input string: "123 456"
sscanf(data, "%d %d", &a, &b)
Result: a = 123, b = 456
--- Section 3: snprintf (print to string, not screen) ---
Buffer size: 10 bytes
snprintf(buffer, 10, "Hello, %s!", "World")
Result: "Hello, Wo"
Wanted length: 13 (truncated because buffer is only 10 bytes)
Asks for input — sample input is one click away
9
String Reading with fgets
Safe string input using fgets instead of the dangerous gets function, with buffer size handling.
03-more-basic-input-output.c76 lines
/* * 03-more-basic-input-output.c — Safe string input with fgets instead of gets * * Key concepts: fgets, buffer overflow protection, gets vs fgets * Compile: gcc -o prog 03-more-basic-input-output.c * Run: ./prog */// to write the same program in c://https://en.cppreference.com/w/c/io //IMPORTANT#include <stdio.h>int main(){ printf("\n"); printf("══════════════════════════════════════\n"); printf(" Safe string input with fgets instead of gets\n"); printf("══════════════════════════════════════\n\n"); printf("\n"); // --- Section 1: gets vs fgets --- printf("--- Section 1: gets() vs fgets() ---\n\n"); // 1. gets = not recommended, not safe // it keeps reading chars regardless of buffer size until \n or \0 char buffer[100]; printf(" [gets] Enter a string (WARNING: gets has no size limit!): "); fflush(stdout); gets(buffer); // Unsafe usage printf(" [gets] You entered: \"%s\"\n", buffer); printf(" NOTE: gets() can overflow the buffer — NEVER use in real code!\n\n"); // fgets is the safe alternative char buffer_2[100]; printf(" [fgets] Enter a string (safe — limited to buffer size): "); fflush(stdout); fgets(buffer_2, sizeof(buffer_2), stdin); // Safe usage printf(" [fgets] You entered: \"%s\"", buffer_2); printf(" NOTE: fgets() includes the \\n in the result\n\n"); // --- Section 2: Reading single characters --- printf("--- Section 2: Reading single characters ---\n\n"); char ch; printf(" Enter a single character: "); fflush(stdout); scanf("%c", &ch); printf(" scanf(\"%%c\") read: '%c' (ASCII %d)\n", ch, ch); // Swallow the leftover newline from pressing Enter scanf("%c", &ch); char ch_2; printf(" Enter another character (using getchar): "); fflush(stdout); ch_2 = getchar(); printf(" getchar() read: '%c' (ASCII %d)\n\n", ch_2, ch_2); // --- Section 3: printf string formatting --- printf("--- Section 3: printf string formatting ---\n\n"); const char* s = "Hello"; printf(" String: \"%s\"\n\n", s); printf(" %-15s | %s\n", "Format", "Output"); printf(" --------------- | ------\n"); printf(" %%s | [%s]\n", s); printf(" %%10s (right) | [%10s]\n", s); printf(" %%-10s (left) | [%-10s]\n", s); printf(" %%.3s (3 chars) | [%.3s]\n", s); printf(" %%10.3s | [%10.3s]\n", s); printf(" %%*s (* = 10) | [%*s]\n\n", 10, s);}
══════════════════════════════════════
Safe string input with fgets instead of gets
══════════════════════════════════════
--- Section 1: gets() vs fgets() ---
[gets] Enter a string (WARNING: gets has no size limit!): hello gets
hello fgets
A
B
[gets] You entered: "hello gets"
NOTE: gets() can overflow the buffer — NEVER use in real code!
[fgets] Enter a string (safe — limited to buffer size): [fgets] You entered: "hello fgets
" NOTE: fgets() includes the \n in the result
--- Section 2: Reading single characters ---
Enter a single character: scanf("%c") read: 'A' (ASCII 65)
Enter another character (using getchar): getchar() read: 'B' (ASCII 66)
--- Section 3: printf string formatting ---
String: "Hello"
Format | Output
--------------- | ------
%s | [Hello]
%10s (right) | [ Hello]
%-10s (left) | [Hello ]
%.3s (3 chars) | [Hel]
%10.3s | [ Hel]
%*s (* = 10) | [ Hello]
Asks for input — sample input is one click awaygets() was removed in C11 — compiled with -std=gnu99 so the unsafe version still builds (expect a warning)
10
File I/O Basics
File operations with fopen, fclose, fprintf, and fscanf — the C equivalent of C++ fstream.
04-basic-files-ptrs.c113 lines
/* * 04-basic-files-ptrs.c — File I/O — fopen, fclose, fprintf, fscanf * * Key concepts: fopen, fclose, fprintf, fscanf, file modes * Compile: gcc -o prog 04-basic-files-ptrs.c * Run: ./prog *//* OLD EXAMPLE OF HOW WE WOULD USE FILES IN LEGACY CPP:int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" File I/O\n"); printf("══════════════════════════════════════\n\n"); // Writing to a file std::ofstream outFile("example.txt"); if (outFile.is_open()) { outFile << "Hello, this is a test file.\n"; outFile << "Writing another line."; outFile.close(); // Explicit close is optional due to RAII } else { std::cerr << "Unable to open file for writing.\n"; } // Reading from a file std::ifstream inFile("example.txt"); std::string line; if (inFile.is_open()) { while (getline(inFile, line)) { std::cout << line << '\n'; } inFile.close(); // Explicit close is optional due to RAII } else { std::cerr << "Unable to open file for reading.\n"; } return 0;}*///in C it will look like this:#include <stdio.h>#include <stdlib.h>int main() { printf("\n"); // --- Section 1: Write to a file --- printf("--- Section 1: Writing to a file (mode \"w\") ---\n\n"); FILE *outFile = fopen("example.txt", "w"); if (outFile != NULL) { fprintf(outFile, "Hello, this is a test file.\n"); fprintf(outFile, "Writing another line."); fclose(outFile); printf(" Wrote 2 lines to example.txt\n\n"); } else { perror(" ERROR: Unable to open file for writing"); } // --- Section 2: Read from a file --- printf("--- Section 2: Reading from a file (mode \"r\") ---\n\n"); FILE *inFile = fopen("example.txt", "r"); char buffer[255]; if (inFile != NULL) { printf(" Contents of example.txt:\n"); while (fgets(buffer, sizeof(buffer), inFile)) { printf(" > %s", buffer); } printf("\n\n"); fclose(inFile); } else { perror(" ERROR: Unable to open file for reading"); } // --- Section 3: Read + Write with fseek --- printf("--- Section 3: Read+Write mode (\"r+\") with fseek ---\n\n"); FILE *file = fopen("example.txt", "r+"); if (file != NULL) { // Seek to end, then append fseek(file, 0, SEEK_END); fprintf(file, "\nAppending a new line.\n"); printf(" Appended a line using fseek(SEEK_END)\n\n"); // Try reading without seeking back — nothing will print printf(" Reading WITHOUT seeking back to start:\n"); int count = 0; while (fgets(buffer, sizeof(buffer), file)) { count++; printf(" > %s", buffer); } if (count == 0) printf(" (nothing — file pointer is at the end!)\n"); printf("\n"); // Now seek to beginning and read fseek(file, 0, SEEK_SET); printf(" Reading AFTER fseek(SEEK_SET) — back to start:\n"); while (fgets(buffer, sizeof(buffer), file)) { printf(" > %s", buffer); } printf("\n"); fclose(file); } else { perror(" ERROR: Unable to open file"); } return 0;}
Editing — changes sent to terminal on Run
$ gcc -o file_io 04-basic-files-ptrs.c
$ ./file_io
Expected Outputclick Run to execute live
--- Section 1: Writing to a file (mode "w") ---
Wrote 2 lines to example.txt
--- Section 2: Reading from a file (mode "r") ---
Contents of example.txt:
> Hello, this is a test file.
> Writing another line.
--- Section 3: Read+Write mode ("r+") with fseek ---
Appended a line using fseek(SEEK_END)
Reading WITHOUT seeking back to start:
(nothing — file pointer is at the end!)
Reading AFTER fseek(SEEK_SET) — back to start:
> Hello, this is a test file.
> Writing another line.
> Appending a new line.
Asks for input
11
Structs with File I/O
Reading and writing struct data to files, combining struct definitions with file operations.
05-more-files-struct.c108 lines
/* * 05-more-files-struct.c — Reading/writing structs to files * * Key concepts: structs, fwrite, fread, file I/O with structured data * Compile: gcc -o prog 05-more-files-struct.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <string.h>const int EMPLOYEE_COUNT = 3;const int MAX_NAME_LENGTH = 50;int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Reading/writing structs to files\n"); printf("══════════════════════════════════════\n\n"); //### Althourgh this doesnt compile on my window gcc // but it does compile on the HAC linux gcc environment struct Employee { int id; char name[MAX_NAME_LENGTH]; float salary; }; // int array[EMPLOYEE_COUNT]; // this does compile: // int array[EMPLOYEE_COUNT]; //ALTHOURGH ON MOST GCC ON WINDOWS IT WONT COMPILE // Creating an array of employees // struct Employee employees[EMPLOYEE_COUNT] = { // {1, "Alice", 55000.00}, // {2, "Bob", 60000.00}, // {3, "Charlie", 50000.00} // }; // we cant use const with object variables so we do dynamic allocation: struct Employee *employees = (struct Employee *)malloc(EMPLOYEE_COUNT * sizeof(struct Employee)); if (employees == NULL) { perror("Unable to allocate memory"); return 1; } // now put the values in the array: employees[0].id = 1; strcpy(employees[0].name, "Alice"); employees[0].salary = 55000.00; employees[1].id = 2; strcpy(employees[1].name, "Bob"); employees[1].salary = 60000.00; employees[2].id = 3; strcpy(employees[2].name, "Charlie"); employees[2].salary = 50000.00; // Writing the array of structures to a text file FILE *outFile = fopen("employees.txt", "w"); if (outFile == NULL) { perror("Unable to open file for writing"); return 1; } for (int i = 0; i < 3; i++) { if (fprintf(outFile, "%d %s %.2f\n", employees[i].id, employees[i].name, employees[i].salary) < 0) { perror("Error writing to file"); return 1; } } fclose(outFile); // Reading the data back into another array struct Employee readEmployees[3]; FILE *inFile = fopen("employees.txt", "r"); if (inFile == NULL) { perror("Unable to open file for reading"); return 1; } //in some c compilers they will not like int i inside the loop //so might need to declare i before the loop for (int i = 0; i < 3; i++) { int itemRead = fscanf(inFile, "%d %s %f", &readEmployees[i].id, readEmployees[i].name, &readEmployees[i].salary); //fscan aswell as fscanf returns the number of items it read int itemsRead = fscanf(inFile, "%d %s %f", &readEmployees[i].id, readEmployees[i].name, &readEmployees[i].salary); if (itemRead != 3) { // Handle the error or unexpected file format } } fclose(inFile); // Displaying the read data printf("\n"); printf("--- Wrote %d employees to employees.txt ---\n\n", EMPLOYEE_COUNT); printf("--- Read them back: ---\n\n"); printf(" %-4s | %-10s | %s\n", "ID", "Name", "Salary"); printf(" ---- | ---------- | ----------\n"); for (int i = 0; i < 3; i++) { printf(" %-4d | %-10s | $%.2f\n", readEmployees[i].id, readEmployees[i].name, readEmployees[i].salary); } printf("\n"); // need to free the memory: free(employees); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o files_struct 05-more-files-struct.c
$ ./files_struct
Expected Outputclick Run to execute live
══════════════════════════════════════
Reading/writing structs to files
══════════════════════════════════════
--- Wrote 3 employees to employees.txt ---
--- Read them back: ---
ID | Name | Salary
---- | ---------- | ----------
1 | Alice | $55000.00
2 | Bob | $60000.00
3 | Charlie | $50000.00
Asks for input
12
Complex Format Specifiers
Advanced printf/scanf formatting: width, precision, padding, and field alignment.
06-complex-usage-scanf-printf.c75 lines
/* * 06-complex-usage-scanf-printf.c — Advanced scanf/printf formatting — width, precision, flags * * Key concepts: format specifiers, width modifiers, precision * Compile: gcc -o prog 06-complex-usage-scanf-printf.c * Run: ./prog */// to write the same program in c:// https://en.cppreference.com/w/c/io //IMPORTANT#include <stdio.h>int main(){ printf("\n"); printf("══════════════════════════════════════\n"); printf(" Advanced scanf/printf formatting\n"); printf("══════════════════════════════════════\n\n"); printf("\n"); // --- Section 1: Multi-type scanf --- printf("--- Section 1: Reading multiple types at once ---\n\n"); int integer; float realNumber; char character; char string[100]; printf(" Enter: integer float char string (e.g., 42 3.14 A hello): "); fflush(stdout); scanf("%d %f %c %s", &integer, &realNumber, &character, string); printf("\n %-12s | %s\n", "Type", "Value"); printf(" ------------ | -----\n"); printf(" %%d (int) | %d\n", integer); printf(" %%f (float) | %.2f\n", realNumber); printf(" %%c (char) | '%c'\n", character); printf(" %%s (string) | \"%s\"\n\n", string); // --- Section 2: Precision and width --- printf("--- Section 2: Precision and width formatting ---\n\n"); double pi = 3.141592653589793; int number = 50; printf(" Pi with different precision:\n"); printf(" %%.2f -> %.2f\n", pi); printf(" %%.5f -> %.5f\n", pi); printf(" %%.10f -> %.10f\n\n", pi); printf(" Width formatting (| shows boundaries):\n"); printf(" %%10d (right-aligned) -> |%10d|\n", number); printf(" %%-10d (left-aligned) -> |%-10d|\n\n", number); // --- Section 3: Parsing a date string --- printf("--- Section 3: Parsing a formatted string ---\n\n"); char line[256]; int day, year; char month[20]; fgetc(stdin); // Consume leftover newline from previous scanf printf(" Enter a date (e.g., January 1, 2020): "); fflush(stdout); fgets(line, sizeof(line), stdin); sscanf(line, "%s %d, %d", month, &day, &year); printf("\n Parsed result:\n"); printf(" Month: %s\n", month); printf(" Day: %d\n", day); printf(" Year: %d\n", year); if (year == 0) printf(" NOTE: Year is 0 — did you forget the comma?\n"); printf("\n========================================\n"); printf(" End of demo\n");}
══════════════════════════════════════
Advanced scanf/printf formatting
══════════════════════════════════════
--- Section 1: Reading multiple types at once ---
Enter: integer float char string (e.g., 42 3.14 A hello): 42 3.14 A hello
March 5, 2024
Type | Value
------------ | -----
%d (int) | 42
%f (float) | 3.14
%c (char) | 'A'
%s (string) | "hello"
--- Section 2: Precision and width formatting ---
Pi with different precision:
%.2f -> 3.14
%.5f -> 3.14159
%.10f -> 3.1415926536
Width formatting (| shows boundaries):
%10d (right-aligned) -> | 50|
%-10d (left-aligned) -> |50 |
--- Section 3: Parsing a formatted string ---
Enter a date (e.g., January 1, 2020):
Parsed result:
Month: March
Day: 5
Year: 2024
========================================
End of demo
Asks for input — sample input is one click away
13
More Complex Formatting
Parsing mixed-type input with sscanf, handling whitespace in format strings, and using scansets to extract substrings.
07-another-complex.c79 lines
/* * 07-another-complex.c — More complex scanf/printf patterns * * Key concepts: format strings, type modifiers * Compile: gcc -o prog 07-another-complex.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" More complex scanf/printf patterns\n"); printf("══════════════════════════════════════\n\n"); char *line = NULL; // Pointer to the buffer allocated by getline size_t len = 0; // Size of the allocated buffer size_t read; // Number of characters read by getline int *grades = NULL; // Array to store grades int numGrades = 0; // Number of grades read char name[100]; // String to store the name printf("\n"); printf(" Example: 90 85 72 John Smith\n\n"); printf(" > "); fflush(stdout); read = getline(&line, &len, stdin); // Read the line if (read == -1) { printf("Failed to read input\n"); return 1; // Exit if input reading fails } // Tokenize the input to separate grades from the name char *token = strtok(line, " \n"); while (token != NULL) { int grade; if (sscanf(token, "%d", &grade) == 1) { // Reallocate grades array to hold new grade int *newGrades = realloc(grades, (numGrades + 1) * sizeof(int)); if (newGrades == NULL) { printf("Failed to allocate memory for grades\n"); free(grades); free(line); return 1; } grades = newGrades; grades[numGrades++] = grade; } else { // Assume the token is part of the name strcpy(name, token); // Collect the remaining part of the name while ((token = strtok(NULL, "\n")) != NULL) { strcat(name, " "); strcat(name, token); } break; } token = strtok(NULL, " \n"); } // Output the results printf("\n --- Parsed Result ---\n\n"); printf(" Name: %s\n", name); printf(" Grades: "); for (int i = 0; i < numGrades; i++) { printf("%d%s", grades[i], (i < numGrades - 1) ? ", " : ""); } printf(" (%d total)\n\n", numGrades); // Clean up free(grades); free(line); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o another_complex 07-another-complex.c
$ ./another_complex
Expected Outputclick Run to execute live
══════════════════════════════════════
More complex scanf/printf patterns
══════════════════════════════════════
Example: 90 85 72 John Smith
> 90 85 72 John Smith
--- Parsed Result ---
Name: John Smith
Grades: 90, 85, 72 (3 total)
Asks for input — sample input is one click away
14
Functions with Pointers
Passing pointers to functions for output parameters — the C pattern for returning multiple values.
08-dont-forget-functions.c103 lines
/* * 08-dont-forget-functions.c — Functions with pointer parameters in C * * Key concepts: pass-by-pointer, function parameters, pointer arithmetic * Compile: gcc -o prog 08-dont-forget-functions.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>int read_line(char **line, size_t *len);int parse_grades_and_name(char *line, int **grades, char *name);void print_results(const char *name, const int *grades, int numGrades);void free_resources(int *grades, char *line);//important details// if you pass a char * to a function,// the function will not be able to change the pointer itself// and will modify a copy of the pointer// if you want to modify the pointer itself, you need to pass a char **//same with gradesint main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Functions with pointer parameters in C\n"); printf("══════════════════════════════════════\n\n"); char *line = NULL; // Pointer to the buffer allocated by getline size_t len = 0; // Size of the allocated buffer int *grades = NULL; // Array to store grades char name[100]; // String to store the name int numGrades; if (read_line(&line, &len) == -1) { printf("Failed to read input\n"); return 1; // Exit if input reading fails } numGrades = parse_grades_and_name(line, &grades, name); print_results(name, grades, numGrades); free_resources(grades, line); return 0;}int read_line(char **line, size_t *len) { printf("\n"); printf(" separate functions using pointer params.\n\n"); printf(" Enter grades followed by a name\n"); printf(" Example: 90 85 72 John Smith\n\n"); printf(" > "); fflush(stdout); size_t read = getline(line, len, stdin); return (read != -1) ? 0 : -1;}int parse_grades_and_name(char *line, int **grades, char *name) { char *token = strtok(line, " \n"); int numGrades = 0; while (token != NULL) { int grade; if (sscanf(token, "%d", &grade) == 1) { int *newGrades = realloc(*grades, (numGrades + 1) * sizeof(int)); if (newGrades == NULL) { printf("Failed to allocate memory for grades\n"); free(*grades); return -1; } *grades = newGrades; (*grades)[numGrades++] = grade; } else { strcpy(name, token); while ((token = strtok(NULL, "\n")) != NULL) { strcat(name, " "); strcat(name, token); } break; } token = strtok(NULL, " \n"); } return numGrades;}void print_results(const char *name, const int *grades, int numGrades) { printf("\n --- Parsed Result ---\n\n"); printf(" Name: %s\n", name); printf(" Grades: "); for (int i = 0; i < numGrades; i++) { printf("%d%s", grades[i], (i < numGrades - 1) ? ", " : ""); } printf(" (%d total)\n\n", numGrades);}void free_resources(int *grades, char *line) { free(grades); free(line);}
Editing — changes sent to terminal on Run
$ gcc -o functions 08-dont-forget-functions.c
$ ./functions
Expected Outputclick Run to execute live
══════════════════════════════════════
Functions with pointer parameters in C
══════════════════════════════════════
separate functions using pointer params.
Enter grades followed by a name
Example: 90 85 72 John Smith
> 90 85 72 John Smith
--- Parsed Result ---
Name: John Smith
Grades: 90, 85, 72 (3 total)
Asks for input — sample input is one click away
15
Advanced Patterns
A multi-struct program that reads structured records from files using fopen/fscanf and processes them with pointer-based functions.
09-last-example.c72 lines
/* * 09-last-example.c — Advanced pointer patterns and string manipulation * * Key concepts: pointers, strings, arrays * Compile: gcc -o prog 09-last-example.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>void initializeData(int **data, int rows, int cols);int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Advanced pointer patterns and string manipulation\n"); printf("══════════════════════════════════════\n\n"); printf("\n"); int rows = 3, cols = 4; printf(" Allocating %dx%d matrix with malloc...\n\n", rows, cols); int **data = malloc(rows * sizeof(int*)); initializeData(data, rows, cols); printf(" Values (data[i][j] = i * %d + j):\n\n", cols); printf(" "); for (int j = 0; j < cols; j++) printf("col%-2d ", j); printf("\n "); for (int j = 0; j < cols; j++) printf("----- "); printf("\n"); for (int i = 0; i < rows; i++) { printf(" row%d |", i); for (int j = 0; j < cols; j++) { printf(" %3d ", data[i][j]); } printf("\n"); } printf("\n========================================\n"); // Free the allocated memory for (int i = 0; i < rows; i++) { free(data[i]); } free(data); return 0;}void initializeData(int **data, int rows, int cols) { // Allocate memory for the array of row pointers if (data == NULL) { perror("Failed to allocate memory for row pointers"); exit(EXIT_FAILURE); } // Allocate memory for each row and initialize values for (int i = 0; i < rows; i++) { (data)[i] = malloc(cols * sizeof(int)); if ((data)[i] == NULL) { perror("Failed to allocate memory for rows"); exit(EXIT_FAILURE); } for (int j = 0; j < cols; j++) { (data)[i][j] = i * cols + j; // Example data } }}