Docsity

fundamentals of programming language, Study notes of C programming

Toggle sidebar
bg1
Preprocessor in C
Before your C program is compiled, it first goes through a preprocessor.
The preprocessor is like a helper that prepares your code for the compiler.
It handles all the lines that start with #(hash symbol).
Ex- #include, #define, #if etc.
Types of Preprocessor Directives in C-
Directive
Purpose
Example
#include
Includes header files
#include <stdio.h>
#define
Defines macros or constants
#define PI 3.14
#undef
Undefines a macro
#undef PI
#ifdef
Checks if a macro is defined
#ifdef DEBUG
#ifndef
Checks if a macro is not defined
#ifndef PI
#if
Tests a condition
#if PI > 3
#else
Alternate code if #if/#ifdef fails
#else
#elif
Else-if condition
#elif PI == 3.14
#endif
Ends conditional directive
#endif
Example 1: #define and #include
#include <stdio.h>
#define PI 3.14159
int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("Area = %.2f\n", area);
return 0;
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

Partial preview of the text

Download fundamentals of programming language and more Study notes C programming in PDF only on Docsity!

Preprocessor in C

Before your C program is compiled , it first goes through a preprocessor. The preprocessor is like a helper that prepares your code for the compiler. It handles all the lines that start with # (hash symbol). Ex- #include, #define, #if etc. Types of Preprocessor Directives in C- Directive Purpose Example #include Includes header files #include <stdio.h> #define Defines macros or constants #define PI 3. #undef Undefines a macro #undef PI #ifdef Checks if a macro is defined #ifdef DEBUG #ifndef Checks if a macro is not defined #ifndef PI #if Tests a condition #if PI > 3 #else Alternate code if #if/#ifdef fails #else #elif Else-if condition #elif PI == 3. #endif Ends conditional directive #endif Example 1: #define and #include #include <stdio.h> #define PI 3. int main() { float radius = 5.0; float area = PI * radius * radius; printf("Area = %.2f\n", area); return 0; }

Example 2: Conditional Compilation #include <stdio.h> #define DEBUG int main() { int a = 10, b = 5; int result = a + b; #ifdef DEBUG printf("DEBUG is defined. value of a is %d, value of b is %d, result is %d",a,b,result); #endif return 0; } Code Explained- #define DEBUG This defines a macro symbol called DEBUG. It doesn’t hold a value — it’s just a flag (a label the preprocessor can check) #ifdef DEBUG printf("Debug: a = %d, b = %d, result = %d\n", a, b, result); #endif #ifdef DEBUG means: If DEBUG is defined, then include the code inside. #endif closes the block. If DEBUG is defined, the debug info will print. If not, it won't.

Files in C: Text and Binary Files

In C, files are used to store and retrieve data permanently. There are two types of files: Text Files Stored in human-readable format (ASCII). You can open, read, or edit them using Notepad or any text editor. Each line ends with a newline character ( \n ).

Syntax- FILE *ptr; ptr = fopen("filename", "mode"); Modes- Mode Meaning "r" Read (file must exist) "w" Write (creates or overwrites) "a" Append (adds at end) "rb" Read binary "wb" Write binary "ab" Append binary Example- FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { printf("File could not be opened.\n"); } Code- fopen() for Writing (Create or Overwrite) #include <stdio.h> int main() { FILE * fp; // Creating a file fp= fopen("file1.txt", "w"); // Checking whether file is created or not if (fp == NULL) {

printf("Error in creating file"); return 1; } printf("File created."); return 0; } What does this mean? fopen("file1.txt", "w") attempts to create and open a file named file1.txt in write mode. If file1.txt doesn’t exist → it will be created. If file1.txt already exists → it will not show an error , but the previous data will be deleted. If for some reason the file cannot be created (e.g., permission issues, full disk, invalid path), fopen will return NULL. file == NULL checks for that error. If the file couldn't be created, it prints an error message and then return 1; is executed. Why return 1? In C, return 0; means success (normal program termination). return 1; (or any non-zero value) means failure or error. It's a way for the program to notify the operating system or calling process that something went wrong.

2. fclose() — Close a File Purpose: Closes an open file and flushes any buffers. Syntax- int fclose(file_pointer);

fprintf(file_pointer, "format", data); Example- fprintf(fp, "Name: %s\nAge: %d\n", "Rutuja", 20); Code- #include <stdio.h> int main() { FILE *fp; // Open the file in write mode fp = fopen("output.txt", "w"); // Check if file opened successfully if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Write formatted data to the file fprintf(fp, "Hello, World!\n"); fprintf(fp, "My name is Rutuja.\n"); fprintf(fp, "I scored %d marks in C programming.\n", 95); // Close the file fclose(fp); printf("Data written to file using fprintf.\n"); return 0; } Explanation fopen("output.txt", "w"): opens (or creates) the file output.txt for writing.

fprintf(fp, ...): writes formatted text to the file , just like printf() does to the screen. fclose(fp): closes the file after writing. Note- If your file already contains some data then it will get overwritten. Code: Write Array Elements to File #include <stdio.h> int main() { FILE *fp; int numbers[] = {10, 20, 30, 40, 50}; int i; // Open file in write mode fp = fopen("array_output.txt", "w"); // Check if file opened successfully if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Write array elements to file fprintf(fp, "Array elements:\n"); for (i = 0; i < 5; i++) { fprintf(fp, "%d\n", numbers[i]); // Each element on a new line } // Close the file

4. fscanf() — Read from a File (Formatted) Purpose: Reads formatted input from a text file , like scanf() does from user. Syntax- int fscanf(file_pointer, format, ...); Example- char name[50]; int age; fscanf(fp, "%s %d", name, &age); ❗ Not safe for lines with spaces (use fgets() instead). Code: Reading an integer and a string from a file using fscanf()- Sample data.txt file content: 21 Rutuja Explanation: 21 → will be stored in the int age Rutuja → will be stored in the char name[50] Code- #include <stdio.h> int main() { FILE *file; int age; char name[50];

// Open the file in read mode file = fopen("data.txt", "r"); // Check if the file opened successfully if (file == NULL) { printf("Error opening file.\n"); return 1; } // Read data from the file using fscanf fscanf(file, "%d %s", &age, name); // Print the read values printf("Age: %d\n", age); printf("Name: %s\n", name); // Close the file fclose(file); return 0; }

5. fgets() — Read a Line from File (Safe) Purpose: Reads a line of text (including spaces) from a file. Syntax: char *fgets(char *str, int n, FILE *stream); Example- char line[100]; fgets(line, sizeof(line), fp);

 fgets() reads a line from the file and stores it in line.  It reads up to sizeof(line)-1 characters or until a newline (\n) or EOF.  The while loop continues until there are no more lines to read (i.e., EOF is reached).  Each line is printed using printf("%s", line);. · sizeof(line) = 100 → meaning fgets() will read up to 99 characters + 1 null terminator ( \0 ) at a time. · The file may contain 1470 characters total , but fgets() doesn’t read the entire file at once — it reads it in chunks of 99 characters per iteration.

6. fputs() — Write a Line to a File Purpose: Writes a string to a file (no formatting). Syntax: int fputs(const char *str, FILE *stream); Example- fputs("Welcome to C programming!\n", fp); Code- #include <stdio.h> int main() { FILE *file; // Open the file in write mode file = fopen("output.txt", "w"); if (file == NULL) { printf("Error opening file.\n"); return 1; } // Write a string to the file using fputs

fputs("Hello, this is a line written using fputs().\n", file); // Close the file fclose(file); printf("Data written to file successfully.\n"); return 0; } Instead of fputs we can use fprintf, fprintf is better than fputs. Function Format Support Example fputs() ❌ No formatting (just strings) fputs("Hello", file); fprintf() ✅ Supports format specifiers like %d, %s, etc. fprintf(file, "Age: %d", 25);

7. fgetc() — Read One Character from File Purpose: Reads a single character from a file. Syntax: int fgetc(FILE *stream); Example- char ch = fgetc(fp); Code- sample.txt content Hello, world! C is fun. #include <stdio.h>

8. fputc() — Write One Character to File Purpose: Writes a single character to a file. Syntax: int fputc(int ch, FILE *stream); Example- fputc('A', fp); Code- #include <stdio.h> int main() { FILE *file; char ch = 'A'; // Open the file in write mode file = fopen("output.txt", "w"); if (file == NULL) { printf("Error opening file.\n"); return 1; } // Write characters to the file using fputc fputc(ch, file); // Write 'A' fputc('\n', file); // Write newline fputc('B', file); // Write 'B' // Close the file fclose(file); printf("Characters written successfully.\n"); return 0; } So using fputc we can’t write -> fputc(“rutuja”,file) 9. fwrite() — Write to a Binary File Purpose: Writes binary data from memory to a file. Syntax:

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream); Parameters explained: Parameter Description ptr Pointer to the data (source) you want to write (e.g., array or variable) size Size of each item in bytes (e.g., sizeof(int)) count Number of items to write stream File pointer to the open file (in "wb" or "ab" mode for binary writing) Example- int numbers[] = {10, 20, 30, 40, 50}; FILE *file = fopen("data.bin", "wb"); fwrite(numbers, sizeof(int), 5, file); // Writes 5 integers (20 bytes total) fclose(file); Code to writing an integer into binary file- #include <stdio.h> int main() { FILE *file; int number = 42; file = fopen("data.bin", "wb"); if (file == NULL) { printf("Error opening file.\n"); return 1; } fwrite(&number, sizeof(int), 1, file); // Writing the integer to file fclose(file);

Code: Reading an integer using fread()- #include <stdio.h> int main() { FILE *file; int number; // Open the file in binary read mode file = fopen("data.bin", "rb"); if (file == NULL) { printf("Error opening file.\n"); return 1; } // Read one integer from the file fread(&number, sizeof(int), 1, file); // Print the number read printf("Number read from file: %d\n", number); // Close the file fclose(file); return 0; } Explanation: fread(&number, sizeof(int), 1, file); Reads 1 block of sizeof(int) bytes from the file into the address of number. So here sizeof(int)=4 bytes. So it will read first block of 4 bytes.

Code for reading 5 integers- #include <stdio.h> int main() { FILE *file; int numbers[5]; // Array to store read data file = fopen("data.bin", "rb"); // Open in read binary mode if (file == NULL) { printf("Error opening file.\n"); return 1; } // Read 5 integers from the file into the array fread(numbers, sizeof(int), 5, file); fclose(file); // Print the values read printf("Data read from file:\n"); for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } return 0; }

12. fseek() — Move File Pointer to Specific Location Purpose: Sets the position of the file pointer. Syntax: