Complete study material – click a topic below to jump to its notes
What is C? C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell Labs in 1972. It was created to write the UNIX operating system. C is often called a "middle-level" language because it combines high-level language features with low-level (assembly-like) capabilities.
Key Features:
Basic Structure of a C Program:
C क्या है? C एक प्रोग्रामिंग भाषा है जिसे 1972 में डेनिस रिची ने बेल लैब्स में बनाया था। इसे UNIX ऑपरेटिंग सिस्टम लिखने के लिए डेवलप किया गया था। C को अक्सर "मिडिल-लेवल" भाषा कहा जाता है क्योंकि यह हाई-लेवल और लो-लेवल (असेंबली जैसी) दोनों तरह की सुविधाएँ देती है।
मुख्य विशेषताएँ:
C प्रोग्राम की बेसिक संरचना:
// My first C program #includeint main() { printf("Hello, World!\n"); return 0; }
Explanation: The #include line tells the compiler to include the standard input/output library. main() is the entry point. printf() prints output. return 0; indicates successful execution.
व्याख्या: #include लाइन कंपाइलर को स्टैंडर्ड इनपुट/आउटपुट लाइब्रेरी शामिल करने के लिए कहती है। main() प्रोग्राम का एंट्री पॉइंट है। printf() आउटपुट प्रिंट करता है। return 0; बताता है कि प्रोग्राम सफलतापूर्वक खत्म हुआ।
Basic Syntax Rules:
// comment. Multi-line: /* comment */.main, Main, and MAIN are different.Tokens in C: A C program consists of various tokens. Tokens can be:
int, return, if, etc.age, sum).10, 3.14, 'A'."Hello".+, -, *.बेसिक सिंटैक्स के नियम:
// कमेंट। एक से ज्यादा लाइनों के लिए: /* कमेंट */।main और Main एक नहीं हैं।C में टोकन: C प्रोग्राम कई टोकन से मिलकर बनता है। टोकन कुछ भी हो सकते हैं:
int, return, if आदि।age, sum).10, 3.14, 'A'।"Hello"।+, -, *।// Program to demonstrate basic syntax #includeint main() { int a = 10; int b = 20; int sum = a + b; printf("Sum is: %d\n", sum); /* This is a multi-line comment It can span several lines */ return 0; }
Explanation: The program declares two integer variables a and b, calculates their sum, and prints it. Notice the semicolons after each statement, the use of // for single-line comments, and /* */ for multi-line comments. The body of main is enclosed in { }.
व्याख्या: इस प्रोग्राम में दो इंटिजर वेरिएबल a और b डिक्लेयर किए गए हैं, उनका योग निकाला गया है और प्रिंट किया गया है। ध्यान दें कि हर स्टेटमेंट के बाद सेमीकोलन है, एक लाइन के कमेंट के लिए // का इस्तेमाल हुआ है और एक से ज्यादा लाइनों के कमेंट के लिए /* */ का। main का बॉडी { } के अंदर है।
What are Data Types? Data types define the type of data a variable can store (e.g., integer, floating-point, character). They also determine how much memory is allocated and what operations can be performed.
Primary Data Types in C:
Derived and User-defined Types:
Type Modifiers: Used with primary types to alter size or range: short, long, signed, unsigned.
डेटा टाइप क्या हैं? डेटा टाइप यह तय करते हैं कि एक वेरिएबल में किस तरह का डेटा स्टोर होगा (जैसे पूर्णांक, दशमलव संख्या, कैरेक्टर)। यह भी बताते हैं कि कितनी मेमोरी लगेगी और उस डेटा पर कौन-कौन से ऑपरेशन किए जा सकते हैं।
C में मुख्य डेटा टाइप:
डिराइव्ड और यूजर-डिफाइंड टाइप:
टाइप मॉडिफायर्स: मुख्य टाइप के साथ उनका साइज या रेंज बदलने के लिए: short, long, signed, unsigned।
// Program to demonstrate data types #includeint main() { int age = 25; float salary = 45000.50; double pi = 3.141592653589; char grade = 'A'; printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); printf("Value of pi: %.10lf\n", pi); printf("Grade: %c\n", grade); unsigned int count = 100; short int small = 32767; printf("Count: %u\n", count); printf("Small: %d\n", small); return 0; }
Explanation: Each variable is declared with a data type. %d, %f, %lf, %c, %u are format specifiers used in printf to print different data types. unsigned means only non-negative values.
व्याख्या: हर वेरिएबल को एक डेटा टाइप के साथ डिक्लेयर किया गया है। %d, %f, %lf, %c, %u फॉर्मेट स्पेसिफायर हैं जो printf में अलग-अलग डेटा टाइप प्रिंट करने के लिए इस्तेमाल होते हैं। unsigned का मतलब सिर्फ पॉजिटिव वैल्यू।
Variables: A variable is a named memory location that stores a value. The value can change during program execution. Variables must be declared before use.
Variable Declaration Syntax: data_type variable_name; or data_type variable_name = initial_value;
Rules for Naming Variables (Identifiers):
int, float, return).age and Age are different.student_age is better than a).Constants: Constants are fixed values that cannot be changed during program execution. There are two ways to define constants:
#define preprocessor: #define PI 3.14159 (no semicolon, usually placed at top).const keyword: const int DAYS = 7; (like a variable but read-only).Scope and Lifetime: Variables have scope (where they are accessible) and lifetime (how long they exist). Local variables are declared inside a function and exist only while the function runs. Global variables are declared outside all functions and exist for the entire program.
वेरिएबल (Variables): वेरिएबल एक नाम दिया गया मेमोरी लोकेशन है जिसमें वैल्यू स्टोर होती है। प्रोग्राम चलते समय इस वैल्यू को बदला जा सकता है। वेरिएबल को इस्तेमाल करने से पहले डिक्लेयर करना पड़ता है।
वेरिएबल डिक्लेरेशन सिंटैक्स: डेटा_टाइप वेरिएबल_नाम; या डेटा_टाइप वेरिएबल_नाम = शुरुआती_मान;
वेरिएबल नाम रखने के नियम (आइडेंटिफायर):
int, float, return) का इस्तेमाल नहीं कर सकते।age और Age अलग-अलग हैं।student_age, a से बेहतर है)।कॉन्स्टैंट्स (Constants): कॉन्स्टैंट वो वैल्यू होती हैं जिन्हें प्रोग्राम चलते समय बदला नहीं जा सकता। कॉन्स्टैंट डिफाइन करने के दो तरीके हैं:
#define प्रीप्रोसेसर का इस्तेमाल: #define PI 3.14159 (कोई सेमीकोलन नहीं, आमतौर पर ऊपर रखते हैं)।const कीवर्ड का इस्तेमाल: const int DAYS = 7; (एक वेरिएबल की तरह लेकिन केवल पढ़ा जा सकता है)।स्कोप और लाइफटाइम: वेरिएबल का स्कोप (कहाँ से एक्सेस कर सकते हैं) और लाइफटाइम (कितनी देर मौजूद रहता है) होता है। लोकल वेरिएबल फंक्शन के अंदर डिक्लेयर होते हैं और सिर्फ तब तक रहते हैं जब तक फंक्शन चल रहा हो। ग्लोबल वेरिएबल सभी फंक्शन के बाहर डिक्लेयर होते हैं और पूरे प्रोग्राम में मौजूद रहते हैं।
// Program to demonstrate variables and constants #include#define PI 3.14159 const int MAX = 100; int global_count = 0; void display() { int local_var = 5; printf("Local variable in display: %d\n", local_var); printf("Global count in display: %d\n", global_count); } int main() { int age = 21; float price = 99.99; char grade = 'B'; printf("Age: %d, Price: %.2f, Grade: %c\n", age, price, grade); age = 22; printf("Updated age: %d\n", age); printf("PI = %f\n", PI); printf("MAX = %d\n", MAX); global_count++; printf("Global count in main: %d\n", global_count); display(); return 0; }
Explanation: Variables age, price, grade are local to main(). global_count is global and accessible in both main() and display(). Constants PI and MAX cannot be changed. #define is a preprocessor directive and does not use memory; const creates a read-only variable.
व्याख्या: age, price, grade वेरिएबल main() के लोकल हैं। global_count ग्लोबल है, इसे main() और display() दोनों में एक्सेस किया जा सकता है। PI और MAX कॉन्स्टैंट हैं, इन्हें बदला नहीं जा सकता। #define एक प्रीप्रोसेसर डायरेक्टिव है, यह मेमोरी नहीं लेता; const से एक रीड-ओनली वेरिएबल बनता है।
Input and Output in C: Input means giving data to the program, output means displaying data from the program. C provides functions for input/output through the standard library <stdio.h>.
Common Output Functions:
printf() – Prints formatted output to the screen (console).puts() – Prints a string followed by a newline.putchar() – Prints a single character.Common Input Functions:
scanf() – Reads formatted input from the keyboard.gets() – Reads a line of text (unsafe, avoid in modern C).getchar() – Reads a single character.Format Specifiers in printf() and scanf(): They specify the type of data to be printed or read.
| Specifier | Data Type | Example |
|---|---|---|
%d or %i |
int | printf("%d", 10); |
%f |
float | printf("%f", 3.14); |
%lf |
double | printf("%lf", 3.14159); |
%c |
char | printf("%c", 'A'); |
%s |
string (char array) | printf("%s", "Hello"); |
%u |
unsigned int | printf("%u", 100); |
Important: In scanf(), you must use the & (address-of) operator before variable names (except for strings/arrays).
C में इनपुट और आउटपुट: इनपुट का मतलब प्रोग्राम को डेटा देना, आउटपुट का मतलब प्रोग्राम से डेटा दिखाना। C में इनपुट/आउटपुट के लिए फंक्शन <stdio.h> लाइब्रेरी में दिए गए हैं।
आम आउटपुट फंक्शन:
printf() – फॉर्मेटेड आउटपुट स्क्रीन पर प्रिंट करता है।puts() – एक स्ट्रिंग और उसके बाद नई लाइन प्रिंट करता है।putchar() – एक अक्षर प्रिंट करता है।आम इनपुट फंक्शन:
scanf() – कीबोर्ड से फॉर्मेटेड इनपुट पढ़ता है।gets() – एक लाइन टेक्स्ट पढ़ता है (असुरक्षित, आधुनिक C में इससे बचें)।getchar() – एक अक्षर पढ़ता है।printf() और scanf() में फॉर्मेट स्पेसिफायर: ये बताते हैं कि किस टाइप का डेटा प्रिंट या रीड करना है।
| स्पेसिफायर | डेटा टाइप | उदाहरण |
|---|---|---|
%d या %i |
int | printf("%d", 10); |
%f |
float | printf("%f", 3.14); |
%lf |
double | printf("%lf", 3.14159); |
%c |
char | printf("%c", 'A'); |
%s |
string (char array) | printf("%s", "Hello"); |
%u |
unsigned int | printf("%u", 100); |
जरूरी: scanf() में वेरिएबल नाम से पहले & (एड्रेस-ऑफ) ऑपरेटर लगाना होता है (स्ट्रिंग/ऐरे को छोड़कर)।
// Program to demonstrate input and output #includeint main() { int age; float height; char initial; char name[50]; printf("Enter your age: "); scanf("%d", &age); printf("Enter your height (in meters): "); scanf("%f", &height); printf("Enter your first initial: "); scanf(" %c", &initial); printf("Enter your full name: "); scanf("%s", name); printf("\n--- Your Details ---\n"); printf("Name: %s\n", name); printf("Age: %d years\n", age); printf("Height: %.2f meters\n", height); printf("Initial: %c\n", initial); printf("\nPress any key to continue..."); char ch = getchar(); ch = getchar(); printf("\nYou pressed: "); putchar(ch); putchar('\n'); return 0; }
Explanation: scanf() reads formatted input. Notice the & before age and height because they are not arrays. For name (a character array), the name itself acts as a pointer, so no & is needed. The space before %c in scanf(" %c", &initial); is to skip any leftover whitespace (like newline) from previous input.
व्याख्या: scanf() फॉर्मेटेड इनपुट पढ़ता है। age और height से पहले & लगाया गया है क्योंकि ये ऐरे नहीं हैं। name (कैरेक्टर ऐरे) के लिए, नाम खुद ही पॉइंटर की तरह काम करता है, इसलिए & नहीं लगाते। scanf(" %c", &initial); में %c से पहले स्पेस देने से पिछले इनपुट का बचा हुआ न्यूलाइन इग्नोर हो जाता है।
What are Operators? Operators are symbols that perform operations on operands (variables and values). C provides a rich set of operators.
Types of Operators in C:
Operator Precedence and Associativity: Determines the order in which operators are evaluated in an expression. For example, multiplication (*) has higher precedence than addition (+). Use parentheses to override precedence.
ऑपरेटर क्या हैं? ऑपरेटर वो चिह्न हैं जो वेरिएबल्स और वैल्यूज पर ऑपरेशन करते हैं। C में कई तरह के ऑपरेटर होते हैं।
C में ऑपरेटर के प्रकार:
ऑपरेटर प्रीसीडेंस और असोसिएटिविटी: यह तय करता है कि किसी एक्सप्रेशन में ऑपरेटरों का मूल्यांकन किस क्रम में होगा। जैसे गुणा (*) का प्रीसीडेंस जोड़ (+) से ज्यादा होता है। प्रीसीडेंस बदलने के लिए ब्रैकेट का इस्तेमाल करें।
// Program to demonstrate various operators #includeint main() { int a = 15, b = 4; printf("Arithmetic Operators:\n"); printf("a + b = %d\n", a + b); printf("a - b = %d\n", a - b); printf("a * b = %d\n", a * b); printf("a / b = %d\n", a / b); printf("a %% b = %d\n", a % b); printf("\nRelational Operators:\n"); printf("a == b = %d\n", a == b); printf("a != b = %d\n", a != b); printf("a > b = %d\n", a > b); printf("a < b = %d\n", a < b); int x = 5, y = 10; printf("\nLogical Operators:\n"); printf("(x < y) && (x > 0) = %d\n", (x < y) && (x > 0)); printf("(x > y) || (y > 0) = %d\n", (x > y) || (y > 0)); printf("!(x == y) = %d\n", !(x == y)); int c = 10; printf("\nAssignment Operators:\n"); c += 5; printf("c += 5 => c = %d\n", c); c *= 2; printf("c *= 2 => c = %d\n", c); int count = 5; printf("\nIncrement/Decrement:\n"); printf("count = %d\n", count); printf("count++ = %d\n", count++); printf("After count++ = %d\n", count); printf("++count = %d\n", ++count); int age = 20; char *status = (age >= 18) ? "Adult" : "Minor"; printf("\nConditional Operator:\n"); printf("Age %d is %s\n", age, status); printf("\nsizeof Operator:\n"); printf("Size of int: %lu bytes\n", sizeof(int)); printf("Size of float: %lu bytes\n", sizeof(float)); return 0; }
Explanation: The program demonstrates each category of operators. Note that integer division truncates the decimal part. The modulus operator % gives the remainder. Relational and logical operators return 1 (true) or 0 (false). The increment/decrement operators can be prefix or postfix, affecting when the value is changed. The conditional operator is a shorthand for if-else.
व्याख्या: यह प्रोग्राम हर तरह के ऑपरेटर का उदाहरण दिखाता है। ध्यान रहे कि इंटिजर डिविजन में दशमलव भाग कट जाता है। मॉड्यूलस ऑपरेटर % शेषफल देता है। रिलेशनल और लॉजिकल ऑपरेटर 1 (सही) या 0 (गलत) लौटाते हैं। इन्क्रीमेंट/डिक्रीमेंट ऑपरेटर प्रीफिक्स या पोस्टफिक्स हो सकते हैं, जिससे वैल्यू बदलने का समय प्रभावित होता है। कंडीशनल ऑपरेटर if-else का शॉर्टकट है।
What are Control Structures? Control structures determine the flow of execution in a program. They allow you to make decisions and execute different blocks of code based on conditions.
Types of Control Structures in C:
कंट्रोल स्ट्रक्चर क्या हैं? कंट्रोल स्ट्रक्चर प्रोग्राम के फ्लो को तय करते हैं, यानी कब कौन सा कोड चलेगा। यह कंडीशन के आधार पर अलग-अलग ब्लॉक चलाने की सुविधा देते हैं।
C में कंट्रोल स्ट्रक्चर के प्रकार:
// Program to demonstrate control structures #includeint main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num > 0) { printf("%d is positive\n", num); } if (num % 2 == 0) { printf("%d is even\n", num); } else { printf("%d is odd\n", num); } if (num < 0) { printf("%d is negative\n", num); } else if (num == 0) { printf("You entered zero\n"); } else { printf("%d is positive (already checked)\n", num); } if (num != 0) { if (num > 100) { printf("%d is greater than 100\n", num); } else { printf("%d is not greater than 100\n", num); } } int choice; printf("\nMenu:\n"); printf("1. Say Hello\n"); printf("2. Say Goodbye\n"); printf("3. Say Hi\n"); printf("Enter your choice (1-3): "); scanf("%d", &choice); switch (choice) { case 1: printf("Hello!\n"); break; case 2: printf("Goodbye!\n"); break; case 3: printf("Hi!\n"); break; default: printf("Invalid choice!\n"); } return 0; }
Explanation: The program first checks if a number is positive (simple if). Then it checks even/odd using if-else. The else-if ladder categorizes negative, zero, or positive. Nested if checks if the number is greater than 100 (only if non-zero). Finally, the switch statement provides a menu-driven interface. Notice the break after each case to prevent fall-through.
व्याख्या: पहले सिंपल if से चेक किया कि नंबर पॉजिटिव है या नहीं। फिर if-else से सम/विषम चेक किया। else-if सीढ़ी से नेगेटिव, जीरो या पॉजिटिव का पता लगाया। नेस्टेड if से चेक किया (सिर्फ नॉन-जीरो होने पर) कि नंबर 100 से बड़ा है या नहीं। आखिर में switch स्टेटमेंट से मेनू दिखाया। हर case के बाद break लगाना जरूरी है ताकि अगला case न चले।
What are Loops? Loops are used to execute a block of code repeatedly as long as a given condition is true. They are essential for tasks that require repetition, like processing arrays or performing iterative calculations.
Types of Loops in C:
Loop Control Statements:
break – Terminates the loop immediately and transfers control to the next statement after the loop.continue – Skips the rest of the current iteration and jumps to the next iteration.लूप्स क्या हैं? लूप्स का इस्तेमाल किसी ब्लॉक को बार-बार चलाने के लिए होता है, जब तक कोई शर्त सही रहे। यह उन कामों के लिए जरूरी हैं जिनमें दोहराव होता है, जैसे ऐरे को प्रोसेस करना या बार-बार कैलकुलेशन करना।
C में लूप्स के प्रकार:
लूप कंट्रोल स्टेटमेंट:
break – लूप को तुरंत खत्म करता है और कंट्रोल लूप के बाहर चला जाता है।continue – मौजूदा इटरेशन का बाकी कोड स्किप करके अगले इटरेशन पर चला जाता है।// Program to demonstrate loops #includeint main() { printf("while loop: "); int i = 1; while (i <= 5) { printf("%d ", i); i++; } printf("\n"); printf("do-while loop: "); int j = 1; do { printf("%d ", j); j++; } while (j <= 5); printf("\n"); printf("for loop: "); for (int k = 1; k <= 5; k++) { printf("%d ", k); } printf("\n"); printf("\nNested loops - pattern:\n"); for (int row = 1; row <= 5; row++) { for (int col = 1; col <= row; col++) { printf("* "); } printf("\n"); } printf("\nbreak example: "); for (int i = 1; i <= 5; i++) { if (i == 3) break; printf("%d ", i); } printf("(loop stopped at 3)\n"); printf("continue example: "); for (int i = 1; i <= 5; i++) { if (i == 3) continue; printf("%d ", i); } printf("(3 is skipped)\n"); return 0; }
Explanation: The program demonstrates each type of loop. The while and for loops check the condition first; the do-while loop executes the body once before checking. Nested loops are used to print a right‑angle triangle of stars. break immediately exits the loop; continue skips the current iteration and moves to the next.
व्याख्या: इस प्रोग्राम में हर तरह के लूप का उदाहरण दिया गया है। while और for लूप पहले कंडीशन चेक करते हैं; do-while लूप एक बार चलता है फिर कंडीशन चेक करता है। नेस्टेड लूप्स से सितारों का त्रिभुज बनाया गया है। break से लूप तुरंत खत्म हो जाता है; continue से मौजूदा इटरेशन छूट जाता है और अगला चलता है।
What are Arrays? An array is a collection of elements of the same data type stored in contiguous memory locations. It allows you to store multiple values under a single variable name, accessed by an index.
Key Points:
data_type array_name[size];int numbers[5] = {10, 20, 30, 40, 50};array_name[index]Types of Arrays:
ऐरे क्या हैं? ऐरे एक ही डेटा टाइप के कई एलिमेंट्स का समूह होता है, जो मेमोरी में लगातार (कॉन्टिग्युअस) स्टोर होते हैं। इससे एक ही नाम से कई वैल्यू स्टोर की जा सकती हैं, और उन्हें इंडेक्स से एक्सेस किया जाता है।
मुख्य बातें:
डेटा_टाइप ऐरे_नाम[साइज];int numbers[5] = {10, 20, 30, 40, 50};ऐरे_नाम[इंडेक्स]ऐरे के प्रकार:
// Program to demonstrate arrays #includeint main() { int numbers[5] = {10, 20, 30, 40, 50}; printf("First element: %d\n", numbers[0]); printf("Third element: %d\n", numbers[2]); numbers[1] = 25; printf("Modified second element: %d\n", numbers[1]); printf("\nAll elements: "); for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } printf("\n"); int scores[] = {95, 87, 92, 78, 88, 91}; int size = sizeof(scores) / sizeof(scores[0]); printf("\nScores (%d elements): ", size); for (int i = 0; i < size; i++) { printf("%d ", scores[i]); } printf("\n"); int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; printf("\n2D Array (3x3 matrix):\n"); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { printf("%d ", matrix[row][col]); } printf("\n"); } int sum = 0; for (int i = 0; i < size; i++) { sum += scores[i]; } printf("\nSum of scores: %d\n", sum); int userArray[5]; printf("\nEnter 5 integers:\n"); for (int i = 0; i < 5; i++) { printf("Element %d: ", i+1); scanf("%d", &userArray[i]); } printf("You entered: "); for (int i = 0; i < 5; i++) { printf("%d ", userArray[i]); } printf("\n"); return 0; }
Explanation: The program demonstrates basic array operations. numbers[5] is a fixed-size array. scores[] size is determined automatically. sizeof(scores) / sizeof(scores[0]) calculates the number of elements. A 2D array matrix[3][3] is printed using nested loops. The program also shows how to calculate sum and take user input into an array.
व्याख्या: प्रोग्राम बेसिक ऐरे ऑपरेशन दिखाता है। numbers[5] एक फिक्स्ड-साइज ऐरे है। scores[] का साइज ऑटोमैटिक डिटेक्ट होता है। sizeof(scores) / sizeof(scores[0]) से एलिमेंट्स की संख्या निकाली गई है। 2D ऐरे matrix[3][3] को नेस्टेड लूप से प्रिंट किया गया है। साथ ही योग निकालना और यूजर से इनपुट लेकर ऐरे में स्टोर करना भी दिखाया गया है।
What are Strings? In C, a string is a sequence of characters stored as an array of characters terminated by a null character '\0'. The null terminator marks the end of the string.
String Declaration and Initialization:
char str[6] = "Hello"; (size includes the null terminator)char str[] = "Hello"; (compiler calculates size)char str[] = {'H','e','l','l','o','\0'};char *str = "Hello"; (string literal – usually read-only)Important String Functions (from <string.h>):
strlen(str) – Returns length of string (excluding null).strcpy(dest, src) – Copies src to dest.strncpy(dest, src, n) – Copies at most n characters.strcat(dest, src) – Appends src to dest.strncat(dest, src, n) – Appends at most n characters.strcmp(str1, str2) – Compares two strings lexicographically. Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2.strncmp(str1, str2, n) – Compares first n characters.strchr(str, ch) – Finds first occurrence of ch in str.strstr(str, substr) – Finds first occurrence of substr in str.strtok(str, delimiters) – Splits string into tokens.Input/Output for Strings:
printf("%s", str); – Prints string.scanf("%s", str); – Reads a word (stops at whitespace).fgets(str, size, stdin); – Reads a line including spaces (safer).puts(str); – Prints string followed by newline.gets(str) – Unsafe, never use.स्ट्रिंग्स क्या हैं? C में, स्ट्रिंग कैरेक्टर्स का एक क्रम होती है जो एक कैरेक्टर ऐरे में स्टोर होती है और उसके अंत में नल कैरेक्टर '\0' होता है। यह नल टर्मिनेटर स्ट्रिंग के खत्म होने का संकेत है।
स्ट्रिंग डिक्लेरेशन और इनिशियलाइजेशन:
char str[6] = "Hello"; (साइज में नल भी शामिल है)char str[] = "Hello"; (कंपाइलर खुद साइज निकाल लेगा)char str[] = {'H','e','l','l','o','\0'};char *str = "Hello"; (यह स्ट्रिंग लिटरल है, आमतौर पर इसे बदला नहीं जा सकता)महत्वपूर्ण स्ट्रिंग फंक्शन (<string.h> से):
strlen(str) – स्ट्रिंग की लंबाई बताता है (नल को छोड़कर)।strcpy(dest, src) – src को dest में कॉपी करता है।strncpy(dest, src, n) – ज्यादा से ज्यादा n कैरेक्टर कॉपी करता है।strcat(dest, src) – src को dest के अंत में जोड़ता है।strncat(dest, src, n) – ज्यादा से ज्यादा n कैरेक्टर जोड़ता है।strcmp(str1, str2) – दो स्ट्रिंग्स की तुलना करता है। बराबर होने पर 0 लौटाता है, str1 छोटी होने पर नेगेटिव, बड़ी होने पर पॉजिटिव।strncmp(str1, str2, n) – पहले n कैरेक्टर की तुलना करता है।strchr(str, ch) – str में ch पहली बार कहाँ मिलता है, वह पता बताता है।strstr(str, substr) – str में substr पहली बार कहाँ मिलता है।strtok(str, delimiters) – स्ट्रिंग को टोकन में तोड़ता है।स्ट्रिंग के लिए इनपुट/आउटपुट:
printf("%s", str); – स्ट्रिंग प्रिंट करता है।scanf("%s", str); – एक शब्द पढ़ता है (स्पेस आते ही रुक जाता है)।fgets(str, size, stdin); – एक पूरी लाइन पढ़ता है (स्पेस सहित) – यह सुरक्षित तरीका है।puts(str); – स्ट्रिंग और उसके बाद नई लाइन प्रिंट करता है।gets(str) – असुरक्षित, कभी इस्तेमाल न करें।// Program to demonstrate strings #include#include int main() { char str1[6] = "Hello"; char str2[] = "World"; char str3[] = {'C', ' ', 'P', 'r', 'o', 'g', '\0'}; char *str4 = "Pointer String"; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("str3: %s\n", str3); printf("str4: %s\n", str4); printf("\nLength of str1: %lu\n", strlen(str1)); printf("Length of str2: %lu\n", strlen(str2)); char dest[20]; strcpy(dest, str1); printf("\nAfter strcpy(dest, str1): dest = %s\n", dest); char full[20] = ""; strcpy(full, str1); strcat(full, " "); strcat(full, str2); printf("Concatenated: %s\n", full); if (strcmp(str1, str2) == 0) printf("\nstr1 and str2 are equal\n"); else printf("\nstr1 and str2 are not equal\n"); char input[100]; printf("\nEnter a line of text: "); fgets(input, sizeof(input), stdin); input[strcspn(input, "\n")] = 0; printf("You entered: %s\n", input); char sentence[] = "C programming is fun"; char *token = strtok(sentence, " "); printf("\nTokens:\n"); while (token != NULL) { printf("%s\n", token); token = strtok(NULL, " "); } char text[] = "Hello, welcome to C programming"; char *pos = strchr(text, 'w'); if (pos) printf("\nFirst occurrence of 'w' at position: %ld\n", pos - text); char *sub = strstr(text, "C"); if (sub) printf("First occurrence of \"C\" at position: %ld\n", sub - text); return 0; }
Explanation: The program shows multiple ways to declare strings. strlen() returns length. strcpy() copies strings. strcat() concatenates. strcmp() compares. fgets() safely reads a line including spaces; we remove the trailing newline using strcspn(). strtok() splits a string into tokens based on delimiters. strchr() and strstr() search for characters and substrings.
व्याख्या: प्रोग्राम स्ट्रिंग डिक्लेयर करने के कई तरीके दिखाता है। strlen() लंबाई बताता है। strcpy() स्ट्रिंग कॉपी करता है। strcat() जोड़ता है। strcmp() तुलना करता है। fgets() से सुरक्षित तरीके से स्पेस सहित पूरी लाइन पढ़ी गई है; फिर strcspn() से अंत के न्यूलाइन को हटाया गया है। strtok() स्ट्रिंग को डिलीमीटर के हिसाब से टोकन में तोड़ता है। strchr() और strstr() कैरेक्टर और सबस्ट्रिंग ढूँढने के लिए हैं।
What are Functions? A function is a self-contained block of code that performs a specific task. Functions help in modular programming – breaking a large program into smaller, manageable pieces. They promote code reusability and easier debugging.
Types of Functions:
printf(), scanf(), strlen()).Function Components:
return_type function_name(parameter_list); Example: int add(int a, int b);return_type function_name(parameter_list) {
// body
return value;
}result = add(5, 3);Parameter Passing: In C, parameters are passed by value – a copy of the argument is passed to the function. Changes inside the function do not affect the original variable.
Return Statement: Returns a value from the function to the caller. The return type must match the function's declared return type. If a function does not return anything, its return type is void.
Recursion: A function that calls itself. Useful for problems that can be broken into smaller, similar subproblems (e.g., factorial, Fibonacci).
फंक्शन क्या हैं? फंक्शन कोड का एक ब्लॉक होता है जो कोई खास काम करता है। फंक्शन की मदद से बड़े प्रोग्राम को छोटे-छोटे हिस्सों में बाँटा जा सकता है। इससे कोड दोबारा इस्तेमाल करना और डीबग करना आसान हो जाता है।
फंक्शन के प्रकार:
printf(), scanf(), strlen()).फंक्शन के घटक:
return_type function_name(parameter_list); उदाहरण: int add(int a, int b);return_type function_name(parameter_list) {
// body
return value;
}result = add(5, 3);पैरामीटर पास करना: C में पैरामीटर वैल्यू से पास होते हैं – फंक्शन में वेरिएबल की कॉपी जाती है। इसलिए फंक्शन के अंदर बदलाव करने से असली वेरिएबल पर असर नहीं होता।
रिटर्न स्टेटमेंट: फंक्शन से वापस कोई वैल्यू लौटाता है। रिटर्न टाइप वही होना चाहिए जो डिक्लेरेशन में बताया गया था। अगर फंक्शन कुछ लौटाता नहीं तो उसका रिटर्न टाइप void होता है।
रिकर्शन (Recursion): जब कोई फंक्शन खुद को ही कॉल करता है। यह उन समस्याओं के लिए उपयोगी है जिन्हें छोटी-छोटी समान समस्याओं में तोड़ा जा सके (जैसे फैक्टोरियल, फिबोनाची)।
// Program to demonstrate functions #includeint add(int a, int b); void greet(char name[]); int factorial(int n); void modifyValue(int x); int main() { int sum = add(10, 20); printf("Sum = %d\n", sum); greet("Alice"); int num = 5; printf("\nBefore modifyValue: num = %d\n", num); modifyValue(num); printf("After modifyValue: num = %d (unchanged)\n", num); int fact = factorial(5); printf("\nFactorial of 5 = %d\n", fact); return 0; } int add(int a, int b) { return a + b; } void greet(char name[]) { printf("Hello, %s! Welcome to C functions.\n", name); } void modifyValue(int x) { x = x * 2; printf("Inside modifyValue: x = %d\n", x); } int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); }
Explanation: The program includes function prototypes at the top. add() returns an integer. greet() is a void function (no return value). modifyValue() shows that passing by value does not affect the original variable. factorial() is a recursive function that calls itself until the base case (n <= 1) is reached.
व्याख्या: प्रोग्राम में ऊपर फंक्शन के प्रोटोटाइप दिए गए हैं। add() एक इंटिजर लौटाता है। greet() void फंक्शन है (कुछ नहीं लौटाता)। modifyValue() दिखाता है कि वैल्यू से पास करने पर असली वेरिएबल पर कोई असर नहीं होता। factorial() एक रिकर्सिव फंक्शन है जो खुद को कॉल करता है जब तक बेस केस (n <= 1) न मिल जाए।
What are Pointers? A pointer is a variable that stores the memory address of another variable. Pointers are one of the most powerful features of C, allowing direct memory access and manipulation. They are essential for dynamic memory allocation, array handling, and passing parameters by reference.
Pointer Declaration: data_type *pointer_name;
Example: int *ptr; declares a pointer to an integer.
Pointer Initialization: Assign the address of a variable to the pointer using the address-of operator &.
Example: int x = 10; int *ptr = &x;
Dereferencing: Access the value stored at the address pointed to by the pointer using the dereference operator *.
Example: printf("%d", *ptr); prints the value of x (10).
Pointer Arithmetic: Pointers support arithmetic operations like increment (++), decrement (--), addition, and subtraction. The arithmetic is based on the size of the data type. For an integer pointer, ptr++ moves to the next integer (4 bytes ahead on most systems).
Pointers and Arrays: Array names act as constant pointers to the first element. arr[i] is equivalent to *(arr + i).
Pointers as Function Parameters: Passing pointers to functions allows the function to modify the original variables (pass by reference).
Null Pointer: A pointer that points to nothing. Assigned as ptr = NULL; It's good practice to initialize pointers to NULL and check for NULL before dereferencing.
Pointer to Pointer: A pointer that stores the address of another pointer. Declared as data_type **ptr;
Void Pointer: A generic pointer that can point to any data type. Declared as void *ptr; Must be typecast before dereferencing.
पॉइंटर्स क्या हैं? पॉइंटर एक वेरिएबल होता है जिसमें दूसरे वेरिएबल का मेमोरी एड्रेस स्टोर रहता है। पॉइंटर्स C की सबसे ताकतवर फीचर्स में से हैं, जिनसे सीधे मेमोरी एक्सेस की जा सकती है। यह डायनामिक मेमोरी एलोकेशन, ऐरे हैंडलिंग और रेफरेंस से पैरामीटर पास करने के लिए जरूरी हैं।
पॉइंटर डिक्लेरेशन: डेटा_टाइप *पॉइंटर_नाम;
उदाहरण: int *ptr; – यह एक इंटिजर का पॉइंटर है।
पॉइंटर इनिशियलाइजेशन: एड्रेस-ऑफ ऑपरेटर & की मदद से किसी वेरिएबल का एड्रेस पॉइंटर में डालते हैं।
उदाहरण: int x = 10; int *ptr = &x;
डिरेफरेंसिंग: पॉइंटर में स्टोर एड्रेस पर जो वैल्यू है उसे * ऑपरेटर से एक्सेस करते हैं।
उदाहरण: printf("%d", *ptr); – यह x की वैल्यू 10 प्रिंट करेगा।
पॉइंटर अरिथमेटिक: पॉइंटर्स पर अरिथमेटिक ऑपरेशन (++, --, +, -) किए जा सकते हैं। यह डेटा टाइप के साइज पर आधारित होता है। इंटिजर पॉइंटर के लिए, ptr++ अगले इंटिजर पर चला जाएगा (ज्यादातर सिस्टम में 4 बाइट आगे)।
पॉइंटर्स और ऐरे: ऐरे का नाम पहले एलिमेंट के पॉइंटर की तरह काम करता है। arr[i] और *(arr + i) एक ही हैं।
फंक्शन पैरामीटर के रूप में पॉइंटर्स: फंक्शन में पॉइंटर पास करने से फंक्शन असली वेरिएबल की वैल्यू बदल सकता है (पास बाय रेफरेंस)।
नल पॉइंटर: वह पॉइंटर जो कहीं इंगित नहीं करता। ptr = NULL; से असाइन करते हैं। अच्छा अभ्यास है कि पॉइंटर को NULL से इनिशियलाइज़ करें और डिरेफरेंस करने से पहले NULL चेक करें।
पॉइंटर टू पॉइंटर: वह पॉइंटर जो दूसरे पॉइंटर का एड्रेस स्टोर करता है। डिक्लेरेशन: डेटा_टाइप **ptr;
Void पॉइंटर: एक जेनेरिक पॉइंटर जो किसी भी डेटा टाइप को इंगित कर सकता है। डिक्लेरेशन: void *ptr; डिरेफरेंस करने से पहले टाइपकास्ट करना पड़ता है।
// Program to demonstrate pointers #includevoid swap(int *a, int *b); int main() { int x = 10; int *ptr = &x; printf("Value of x: %d\n", x); printf("Address of x: %p\n", &x); printf("Value of ptr (address it holds): %p\n", ptr); printf("Value pointed to by ptr: %d\n", *ptr); *ptr = 20; printf("\nAfter *ptr = 20, x = %d\n", x); int arr[] = {10, 20, 30, 40, 50}; int *arrPtr = arr; printf("\nArray elements using pointer arithmetic:\n"); for (int i = 0; i < 5; i++) { printf("arr[%d] = %d, *(arrPtr + %d) = %d, arrPtr[%d] = %d\n", i, arr[i], i, *(arrPtr + i), i, arrPtr[i]); } int a = 5, b = 10; printf("\nBefore swap: a = %d, b = %d\n", a, b); swap(&a, &b); printf("After swap: a = %d, b = %d\n", a, b); int *nullPtr = NULL; if (nullPtr == NULL) { printf("\nnullPtr is NULL and points to nothing\n"); } int y = 100; int *ptr1 = &y; int **ptr2 = &ptr1; printf("\nPointer to pointer:\n"); printf("Value of y: %d\n", y); printf("Value using ptr1: %d\n", *ptr1); printf("Value using ptr2: %d\n", **ptr2); int num = 42; float fnum = 3.14; void *vptr; vptr = # printf("\nVoid pointer pointing to int: %d\n", *(int *)vptr); vptr = &fnum; printf("Void pointer pointing to float: %.2f\n", *(float *)vptr); return 0; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
Explanation: The program covers all major pointer concepts. ptr = &x stores address, *ptr accesses value. Pointer arithmetic shows how arrPtr + i moves through the array. The swap() function demonstrates passing pointers to modify original variables. Null pointer check prevents errors. Pointer to pointer (**ptr2) stores address of another pointer. Void pointer (void *vptr) can point to any type but must be cast before dereferencing.
व्याख्या: प्रोग्राम सभी पॉइंटर कॉन्सेप्ट कवर करता है। ptr = &x एड्रेस स्टोर करता है, *ptr वैल्यू एक्सेस करता है। पॉइंटर अरिथमेटिक से दिखाया गया है कि arrPtr + i से ऐरे में कैसे आगे बढ़ते हैं। swap() फंक्शन से पता चलता है कि पॉइंटर पास करके असली वेरिएबल कैसे बदले जाते हैं। नल पॉइंटर चेक से एरर से बचा जा सकता है। पॉइंटर टू पॉइंटर (**ptr2) दूसरे पॉइंटर का एड्रेस रखता है। Void पॉइंटर (void *vptr) किसी भी टाइप को इंगित कर सकता है, लेकिन डिरेफरेंस करने से पहले कास्ट करना होगा।
What are Structures? A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. It is used to represent a record (e.g., a student, an employee, a point in 2D space).
Defining a Structure: Use the struct keyword followed by the structure name and a list of members inside curly braces.
struct structure_name {
data_type member1;
data_type member2;
...
};
Declaring Structure Variables: You can declare variables at the time of definition or later.
Accessing Members: Use the dot operator (.) to access members of a structure variable.
Initialization: You can initialize structure variables at declaration.
Arrays of Structures: You can create an array of structures to store multiple records.
Nested Structures: A structure can contain another structure as a member.
Pointers to Structures: You can have pointers pointing to structure variables. Use arrow operator -> to access members via pointer.
typedef with Structures: typedef can be used to create an alias for a structure, making code cleaner.
स्ट्रक्चर (Structure) क्या है? स्ट्रक्चर C में यूजर-डिफाइंड डेटा टाइप होता है जो अलग-अलग डेटा टाइप के वेरिएबल्स को एक नाम के अंदर समूहित करता है। इसका इस्तेमाल किसी रिकॉर्ड को दर्शाने के लिए होता है (जैसे स्टूडेंट, एम्प्लॉई, 2D स्पेस में एक पॉइंट)।
स्ट्रक्चर डिफाइन करना: struct कीवर्ड, फिर स्ट्रक्चर का नाम, और घुंघराले ब्रेसेस के अंदर मेंबर्स की लिस्ट।
struct स्ट्रक्चर_नाम {
डेटा_टाइप मेंबर1;
डेटा_टाइप मेंबर2;
...
};
स्ट्रक्चर वेरिएबल डिक्लेयर करना: आप डिफाइन करते समय या बाद में वेरिएबल डिक्लेयर कर सकते हैं।
मेंबर्स एक्सेस करना: डॉट ऑपरेटर (.) से स्ट्रक्चर वेरिएबल के मेंबर्स एक्सेस करते हैं।
इनिशियलाइजेशन: डिक्लेरेशन के समय स्ट्रक्चर वेरिएबल को इनिशियलाइज़ कर सकते हैं।
स्ट्रक्चर का ऐरे: एक से ज्यादा रिकॉर्ड स्टोर करने के लिए स्ट्रक्चर का ऐरे बना सकते हैं।
नेस्टेड स्ट्रक्चर: एक स्ट्रक्चर के अंदर दूसरा स्ट्रक्चर मेंबर हो सकता है।
स्ट्रक्चर के पॉइंटर्स: स्ट्रक्चर वेरिएबल को पॉइंटर से इंगित कर सकते हैं। पॉइंटर से मेंबर एक्सेस करने के लिए ऐरो ऑपरेटर -> का इस्तेमाल करते हैं।
typedef के साथ स्ट्रक्चर: typedef से स्ट्रक्चर के लिए उपनाम (alias) बना सकते हैं, जिससे कोड साफ दिखता है।
// Program to demonstrate structures #include#include struct Student { char name[50]; int age; float marks; }; struct Address { char city[50]; int pincode; }; struct Employee { int id; char name[50]; struct Address addr; }; typedef struct Point { int x; int y; } Point; int main() { struct Student s1 = {"Alice", 20, 85.5}; printf("Student 1:\n"); printf("Name: %s\n", s1.name); printf("Age: %d\n", s1.age); printf("Marks: %.2f\n\n", s1.marks); strcpy(s1.name, "Bob"); s1.age = 22; s1.marks = 90.0; printf("After modification:\n"); printf("Name: %s\n", s1.name); printf("Age: %d\n", s1.age); printf("Marks: %.2f\n\n", s1.marks); struct Student class[3] = { {"Charlie", 19, 78.5}, {"David", 21, 88.0}, {"Eve", 20, 92.3} }; printf("Class records:\n"); for (int i = 0; i < 3; i++) { printf("Student %d: %s, Age %d, Marks %.2f\n", i+1, class[i].name, class[i].age, class[i].marks); } printf("\n"); struct Employee emp1; emp1.id = 101; strcpy(emp1.name, "John"); strcpy(emp1.addr.city, "New York"); emp1.addr.pincode = 10001; printf("Employee:\n"); printf("ID: %d\n", emp1.id); printf("Name: %s\n", emp1.name); printf("City: %s, Pincode: %d\n\n", emp1.addr.city, emp1.addr.pincode); struct Student *ptr = &s1; printf("Using pointer to structure:\n"); printf("Name: %s\n", ptr->name); printf("Age: %d\n", ptr->age); printf("Marks: %.2f\n\n", ptr->marks); Point p1 = {10, 20}; printf("Point (typedef): (%d, %d)\n\n", p1.x, p1.y); printf("Size of struct Student: %lu bytes\n", sizeof(struct Student)); printf("Size of int: %lu, float: %lu, char[50]: %lu\n", sizeof(int), sizeof(float), sizeof(char[50])); return 0; }
Explanation: The program demonstrates defining a structure (struct Student), initializing, accessing, and modifying members. It shows an array of structures, a nested structure (struct Employee containing struct Address), and a pointer to structure using the arrow operator ->. typedef simplifies the declaration of struct Point. The sizeof output may show padding bytes.
व्याख्या: यह प्रोग्राम स्ट्रक्चर डिफाइन करना (struct Student), मेंबर्स को इनिशियलाइज़, एक्सेस और मॉडिफाई करना दिखाता है। इसमें स्ट्रक्चर का ऐरे, एक नेस्टेड स्ट्रक्चर (struct Employee जिसमें struct Address है), और ऐरो ऑपरेटर -> से स्ट्रक्चर पॉइंटर का इस्तेमाल दिखाया गया है। typedef से struct Point डिक्लेयर करना आसान हो गया। sizeof से पता चलता है कि स्ट्रक्चर का साइज उसके मेंबर्स के कुल साइज से ज्यादा हो सकता है (पैडिंग की वजह से)।
What is File Handling? File handling in C allows you to create, read, write, and manipulate files on the disk. Files are used to store data permanently, unlike variables which lose data when the program ends.
File Operations: The basic operations on files are:
File Pointer: C uses a pointer of type FILE to handle files. The FILE structure is defined in <stdio.h>.
Opening a File: The fopen() function opens a file and returns a file pointer. Syntax: FILE *fopen(const char *filename, const char *mode);
File Modes:
| Mode | Description |
|---|---|
"r" | Open for reading. File must exist. |
"w" | Open for writing. Creates new file or truncates existing to zero length. |
"a" | Open for appending. Creates new file if it doesn't exist. |
"r+" | Open for reading and writing. File must exist. |
"w+" | Open for reading and writing. Creates new file or truncates existing. |
"a+" | Open for reading and appending. Creates new file if it doesn't exist. |
"rb", "wb", "ab" | Binary modes. |
Closing a File: Always close a file after operations using fclose(). Syntax: int fclose(FILE *stream);
Reading from a File: Common functions:
int fgetc(FILE *fp); – Reads a character.char *fgets(char *str, int n, FILE *fp); – Reads a line.int fscanf(FILE *fp, const char *format, ...); – Reads formatted input.size_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp); – Reads binary data.Writing to a File: Common functions:
int fputc(int ch, FILE *fp); – Writes a character.int fputs(const char *str, FILE *fp); – Writes a string.int fprintf(FILE *fp, const char *format, ...); – Writes formatted output.size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp); – Writes binary data.Error Handling: Check if fopen() returns NULL (indicates failure). Use feof() to check for end-of-file and ferror() to check for errors.
Random Access: Functions like fseek(), ftell(), and rewind() allow moving to specific positions in a file.
फ़ाइल हैंडलिंग क्या है? C में फ़ाइल हैंडलिंग से हम डिस्क पर फ़ाइलें बना सकते हैं, पढ़ सकते हैं, लिख सकते हैं और उनमें बदलाव कर सकते हैं। फ़ाइलों में डेटा स्थायी रूप से स्टोर होता है, जबकि वेरिएबल में डेटा प्रोग्राम खत्म होते ही गायब हो जाता है।
फ़ाइल ऑपरेशन: फ़ाइल पर बेसिक ऑपरेशन:
फ़ाइल पॉइंटर: C में फ़ाइलों को हैंडल करने के लिए FILE टाइप का पॉइंटर इस्तेमाल होता है। FILE स्ट्रक्चर <stdio.h> में डिफाइन है।
फ़ाइल खोलना: fopen() फंक्शन फ़ाइल खोलता है और फ़ाइल पॉइंटर लौटाता है। सिंटैक्स: FILE *fopen(const char *filename, const char *mode);
फ़ाइल मोड:
| मोड | विवरण |
|---|---|
"r" | सिर्फ पढ़ने के लिए। फ़ाइल पहले से मौजूद होनी चाहिए। |
"w" | लिखने के लिए। नई फ़ाइल बनाएगा या पुरानी हो तो उसे खाली कर देगा। |
"a" | जोड़ने के लिए (append)। अगर फ़ाइल नहीं है तो नई बनाएगा। |
"r+" | पढ़ने और लिखने के लिए। फ़ाइल मौजूद होनी चाहिए। |
"w+" | पढ़ने और लिखने के लिए। नई बनाएगा या पुरानी को खाली करेगा। |
"a+" | पढ़ने और जोड़ने के लिए। नई बनाएगा अगर नहीं है। |
"rb", "wb", "ab" | बाइनरी मोड (ऊपर के समान)। |
फ़ाइल बंद करना: हमेशा काम खत्म करने के बाद fclose() से फ़ाइल बंद करें। सिंटैक्स: int fclose(FILE *stream);
फ़ाइल से पढ़ना: सामान्य फंक्शन:
int fgetc(FILE *fp); – एक अक्षर पढ़ता है।char *fgets(char *str, int n, FILE *fp); – एक लाइन पढ़ता है।int fscanf(FILE *fp, const char *format, ...); – फॉर्मेटेड इनपुट पढ़ता है।size_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp); – बाइनरी डेटा पढ़ता है।फ़ाइल में लिखना: सामान्य फंक्शन:
int fputc(int ch, FILE *fp); – एक अक्षर लिखता है।int fputs(const char *str, FILE *fp); – एक स्ट्रिंग लिखता है।int fprintf(FILE *fp, const char *format, ...); – फॉर्मेटेड आउटपुट लिखता है।size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp); – बाइनरी डेटा लिखता है।एरर हैंडलिंग: fopen() अगर NULL लौटाता है तो समझो फ़ाइल नहीं खुली। feof() से फ़ाइल का अंत चेक करते हैं और ferror() से कोई एरर आई है या नहीं।
रैंडम एक्सेस: fseek(), ftell(), rewind() जैसे फंक्शन से फ़ाइल में किसी खास जगह पर जा सकते हैं।
// Program to demonstrate file handling #include#include int main() { FILE *fp; char ch; char str[100]; fp = fopen("test.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); exit(1); } fprintf(fp, "This is a test file.\n"); fprintf(fp, "It contains multiple lines.\n"); fputs("Hello from fputs!\n", fp); fputc('A', fp); fputc('\n', fp); printf("Data written to test.txt successfully.\n"); fclose(fp); fp = fopen("test.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); exit(1); } printf("\nReading file character by character:\n"); while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); fp = fopen("test.txt", "r"); printf("\n\nReading file line by line:\n"); while (fgets(str, sizeof(str), fp) != NULL) { printf("%s", str); } fclose(fp); fp = fopen("test.txt", "a"); if (fp == NULL) { printf("Error opening file for appending!\n"); exit(1); } fprintf(fp, "This line is appended.\n"); printf("\nData appended to test.txt.\n"); fclose(fp); fp = fopen("test.txt", "r"); printf("\nFile after appending:\n"); while (fgets(str, sizeof(str), fp) != NULL) { printf("%s", str); } fclose(fp); fp = fopen("data.txt", "w"); fprintf(fp, "John 25 85.5\n"); fprintf(fp, "Alice 22 92.3\n"); fprintf(fp, "Bob 23 78.9\n"); fclose(fp); fp = fopen("data.txt", "r"); char name[50]; int age; float marks; printf("\n\nReading formatted data from data.txt:\n"); while (fscanf(fp, "%s %d %f", name, &age, &marks) != EOF) { printf("Name: %s, Age: %d, Marks: %.2f\n", name, age, marks); } fclose(fp); fp = fopen("test.txt", "r"); fseek(fp, 5, SEEK_SET); printf("\n\nCharacter at position 5: %c\n", fgetc(fp)); long pos = ftell(fp); printf("Current position: %ld\n", pos); rewind(fp); printf("After rewind, first character: %c\n", fgetc(fp)); fclose(fp); return 0; }
Explanation: The program demonstrates all major file operations. First, it writes to "test.txt" using fprintf(), fputs(), and fputc(). Then it reads the same file character by character using fgetc() and line by line using fgets(). Next, it appends a line to the file. Then it creates a formatted data file and reads it using fscanf(). Finally, it shows file positioning with fseek(), ftell(), and rewind(). Always check if fopen() returns NULL and close files after use.
व्याख्या: प्रोग्राम सभी मुख्य फ़ाइल ऑपरेशन दिखाता है। पहले "test.txt" में fprintf(), fputs(), और fputc() से लिखा गया। फिर उसी फ़ाइल को fgetc() से अक्षर दर अक्षर और fgets() से लाइन दर लाइन पढ़ा गया। फिर एक लाइन append की गई। फिर एक फॉर्मेटेड डेटा फ़ाइल बनाई गई और fscanf() से पढ़ी गई। अंत में fseek(), ftell(), और rewind() से फ़ाइल पोजिशनिंग दिखाई गई। हमेशा fopen() के NULL लौटने की जाँच करें और फ़ाइलों को बंद करें।