[go: up one dir, main page]

0% found this document useful (0 votes)
26 views76 pages

Unit-1.2.pptx Removed

If th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views76 pages

Unit-1.2.pptx Removed

If th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Topics

C Program For Problem-solving-

Basic Structure Of C Program

Executing A C Program

Constant, Variable And Data Types

Type Conversion

Operators And Expressions

Managing Input And Output Operations


HISTORY
&
DEVELOPMENT OF ‘C’
.
Brief History of “C”
🡪“C” programming language was developed by Dennis Ritchie
and Brian Kernighan, at Bell Telephone Laboratories (now AT&T
incorporation US) in 1972.

🡪It was modified from BCPL (Basic Combined Programming


Language), which was developed by Martin Richards.

🡪Later modified by Ken Thompson as B Language.

Finally, to C programming language.

Saurabh Bhattacharya, Assistant Professor, SCSE


BIRTH OF C…
• C is very often referred as a “System Programming
Language” because it is used for writing compilers,
editors and even operating systems.

• C was developed and implemented on the UNIX


operating system on the DEC PDP-11, by Dr.
Dennis M. Ritchie.

• C was evolved during 1971-73 from B language of


Ken Thompson, which was evolved (in 1969-70)
from BCPL language of Martin Richards.
FATHER OF C
Timeline: Development Of Various Language
Advantage with ‘c’
• Compact, fast, and powerful
• “Mid-level” Language
• Standard for program development (wide acceptance)
• It is everywhere! (portable)
• Supports modular programming style
• Useful for all applications
• C is the native language of UNIX
• Easy to interface with system devices/assembly routines
• C is terse (i.e using few words)
Characteristics OF C
•C has facilities for structured programming

•In C, all executable code is contained within functions.

• Heterogeneous aggregate data types (struct) allow related data


elements to be combined and manipulated as a unit.

•C program source text is free-format, using the semicolon (;) as a


statement terminator.

•A large number of compound operators, such as +=, -=, *= and ++


etc.

•Logical "and" and "or" are represented with && and ||.
‘C’
TOKENS
VARIOUS C TOKENS
In a passage of text, individual words and punctuation marks are called
tokens. This are the smallest individual units are known as C tokens. C has
SIX types of tokens,.

C TOKENS

KEYWORDS CONSTANTS SPECIAL


IDENTIFIERS STRINGS OPERATORS
(float, while, do, (25,36.3, SYMBOLS
(main, account) (“ABC”, “year”) (+, -, *, /)
for etc) 2.000e-3) ([, ], {, })
“C” character sets
Keywords(Reserved words)
• Keywords are the words whose meaning has already been
explained to the C compiler.
• The keywords cannot be used as variable names.
• There are only 32 keywords available in C.
Constant
&
Variables
Constants
• Constants are those whose value is fixed, and the value does not change.
• There are 2 types of constants.
• Integer constant and
• Real constant.

i. Fractional Constant
ii. Exponential Constant
Datatypes

Data Types
in C
Enumeration
Basic Data Derived Data User-Defined
and Void
Types Types Data Types
Types
Basic Data Types
• int: Used to store integers (whole numbers). Size: 4 bytes.
• Example: int age = 25;

• float: Used to store single-precision floating-point numbers (decimal


numbers). Size: 4 bytes.
• Example: float salary = 35000.75;

• double: Used to store double-precision floating-point numbers.


Size: 8 bytes.
• Example: double distance = 123456.789;

• char: Used to store single characters. Size: 1 byte.


• Example: char grade = 'A';
Derived Data Types & Enumeration and Void
Types
Derived Data Types
•Arrays: Collection of elements of the same type.
•Example: int arr[5];
•Pointers: Stores the address of another variable.
•Example: int *ptr;
•Functions: Blocks of code that can return values of various
data types.

Enumeration and Void Types


•enum: Used to assign names to integer constants.
•Example: enum day {Mon, Tue, Wed};
•void: Used for functions that do not return a value or as a
pointer type.
•Example: void function();
User-Defined Data Types
• struct: Combines different data types into a single unit.
• Example:
struct Student
{
int roll;
char name[50];
float marks;
};

• union: Stores different data types in the same memory location (one at a
time).
• Example:
union Data
{
int i;
float f;
char str[20];
};
Size and Range
• Size: The size of a data type determines how much memory is allocated for
it in bytes.
• For example, `int` typically takes 4 bytes, `float` takes 4 bytes, and
`double` takes 8 bytes.
• The size can vary depending on the system architecture (32-bit vs
64-bit).

• Range: The range of a data type is the minimum and maximum values it
can hold. It is directly related to the size.
• For example, a 4-byte `int` can store values from -2,147,483,648 to
2,147,483,647, while a `float` can store decimal values between
approximately 3.4E-38 and 3.4E+38.

• Platform Dependency: The size and range of data types may vary slightly
depending on the platform and compiler being used.
• For example, `long int` may be 4 bytes on a 32-bit system but 8 bytes on
a 64-bit system.
Qualifiers
• Signed/Unsigned: These qualifiers modify the range of a data type.
• A signed type can hold both negative and positive values (e.g., `int` is
signed by default), while an unsigned type only holds positive values,
extending the upper limit of the range.
• For example, `unsigned int` can range from 0 to 4,294,967,295.

• Short/Long: These qualifiers adjust the size of the integer data type.
• A short integer uses less memory (typically 2 bytes), and a long integer
allows larger values (typically 8 bytes in a 64-bit system).
• For example, `long int` allows storing larger integers than `int`.

• Volatile/Const: The `volatile` qualifier tells the compiler that the variable's
value can change unexpectedly (e.g., in embedded systems).
• The `const` qualifier indicates that a variable's value cannot be modified
once initialized.
Rules for Constructing Integer Constants
• No decimal point: Integer constants are whole numbers without any decimal
point.

• Positive or negative: They can be either positive or negative. A positive


constant can be written without a sign, but a negative constant must be
prefixed with a minus sign (-).

• Base system support: Integer constants can be expressed in different bases:


• Decimal (Base 10): No prefix (e.g., 10).
• Octal (Base 8): Prefixed with 0 (e.g., 077).
• Hexadecimal (Base 16): Prefixed with 0x or 0X (e.g., 0x7A).

• No commas or spaces: An integer constant cannot contain commas or spaces


(e.g., 1,000 is invalid, 1000 is valid).

• Range limitations: Integer constants must lie within the range defined by the
data type (int, long, etc.), otherwise an overflow error occurs.
Rules for Constructing Real Constants
(Fractional Form)
• Contains a decimal point: A real constant must include a decimal point
(e.g., 3.14).

• Positive or negative: They can be either positive or negative, with the


negative prefixed by a minus sign (-).

• Optional fractional part: The number can have a fractional part after
the decimal point (e.g., 10.0 is valid, as is 0.25).

• No spaces or commas: Real constants must be written as a single


uninterrupted sequence (e.g., 1.2 is valid, 1. 2 is not).

• Optional leading digits: Leading digits before the decimal point can be
omitted if the number starts with 0. (e.g., .5 is valid and represents 0.5).
Rules for Constructing Real Constants
(Exponential Form)
• Exponential notation: Real constants in exponential form are written as mEp
where m is the mantissa and p is the exponent (e.g., 2.5E3 is 2.5 * 10^3).

• Mantissa can be positive or negative: The mantissa can be positive or negative,


with a minus sign (-) used for negatives (e.g., -2.5E4).

• Exponent sign: The exponent part can be positive or negative. A positive


exponent indicates multiplication by powers of 10, while a negative exponent
indicates division (e.g., 1E-3 equals 0.001).

• Decimal point in mantissa: The mantissa may or may not contain a decimal point
(e.g., 1E6 and 1.0E6 are both valid).

• No spaces: There must be no spaces between the mantissa, E, and exponent (e.g.,
1.23 E4 is invalid, but 1.23E4 is valid).
Rules for Constructing Character Constants
• Single character enclosed in single quotes: A character constant is
enclosed in single quotation marks (e.g., 'A’).

• Only one character: It can hold only one character (e.g., 'A' is valid, but
'AB' is invalid).

• ASCII value storage: The character constant stores the ASCII value of
the character, not the character itself.

• Escape sequences allowed: Special characters can be represented using


escape sequences (e.g., '\n' for newline, '\t' for tab).

• Unsigned type: Character constants are of type int, so their values are
stored as integers in the range of valid ASCII values (0-255).
Variables
• In C programming, a variable is a named storage location in the
computer’s memory that can hold a value, which can be modified during
program execution.
• Variables allow programs to store and manipulate data dynamically.
• Key Concepts of Variables:
• Variable Declaration: Before using a variable in a C program, it must
be declared.
• Declaring a variable means specifying its type (what kind of data it
can store) and its name (a unique identifier). For example:
•int age;
•float height;
•char grade;
Rule for creating variable name
• Starts with a letter or underscore: A variable name must start with
either a letter (uppercase or lowercase) or an underscore (_). It cannot
start with a digit. For example, int age; or int _count; are valid, but int
1stNumber; is invalid.
• Only letters, digits, and underscores: A variable name can only consist
of letters (uppercase or lowercase), digits, and underscores. Special
characters like @, #, &, or spaces are not allowed. For example,
total_amount is valid, but total-amount or total amount is invalid.
• Case-sensitive: Variable names are case-sensitive. This means that Sum,
sum, and SUM are considered three different variables.
• No reserved keywords: Variable names cannot be any of the C
language reserved keywords (like int, return, for, etc.). For example, int
return; is invalid because return is a reserved keyword in C.
• Length restrictions: While C allows variable names of any length,
some compilers may only recognize the first 31 characters of an
identifier. Keeping variable names concise yet descriptive is generally a
good practice.
Declaring Variables
A variable is a named memory location in which data of a certain type can be
stored. The contents of a variable can change, thus the name. User defined
variables must be declared before they can be used in a program.

• It is during the declaration phase that the actual memory for the variable is
reserved. All variables in C must be declared before use.
• Get into the habit of declaring variables using lowercase characters.

• Remember that C is case sensitive, so even though the two variables listed

below have the same name, they are considered different variables in C.

sum Sum

• The declaration of variables is done after the opening brace of main().

main()
{
int sum;
Initializing Variables
• C Variables may be initialized with a value when they are declared. Consider
the following declaration, which declares an integer variable count which is
• initialized to 10.
• int count = 10;

• In general, the user should not assume that variables are initialized to some
default value “automatically” by the compiler.

• Programmers must ensure that variables have proper values before they are
used in expressions.
Initializing Variables Example

•The following example illustrates the two methods for variable


initialization:

which produces the following output


ASCII Character Set
INSTRUCTIONS
TYPES OF Instructions

• There are basically three types of instructions in C:


•1.Type Declaration Instruction
•2.Arithmetic Instruction
•3.Control Instruction
• The purpose of each of these instructions is given below:

• Type declaration instruction: To declare the type of variables used in a C


program.

• Arithmetic instruction: To perform arithmetic operations between constants


and variables.

• Control instruction: To control the sequence of execution of various


statements in a C program.
EXPRESSIONS
&
STATEMENTS
Expressions

• An expression in C is some combination of constants, variables, operators


and function calls.
• Sample expressions are:
•a + b
• 3.0*x - 9.66553
• tan(angle)
Statements
• Most expressions have a value based on their contents.
• A statement in C is just an expression terminated with a semicolon.
• Sample Statements:
• sum = x + y + z;
• printf(“WELCOME!");
EXAMPLE:
FIRST “C” PROGRAM
Basic structure of c program
Documentation section
Link section
Definition Section
Global Declaration Section
Main() Function Section
{
Declaration Part
Executable Part

}
Subprogram Section
Function 1
Function 2
(User Defined Functions)
----
----
Function n DEMO
Explanation of the Sections
• Documentation Section: Provides information about what the program does.
Typically, you write comments here to explain the functionality.
• Link Section: Includes necessary libraries using #include statements. In this
example, we include the stdio.h library for input/output functions like printf().
• Definition Section: Contains macro definitions or constants. Here, #define PI
3.14159 defines the value of PI.
• Global Declaration Section: Declares global variables that are accessible throughout
the program, such as global_var.
• Main Function Section: The entry point of the program where the program
execution starts. Inside the main() function, we declare local variables, perform
operations, and call subprograms.
• Subprogram Section: Defines additional functions that are used to modularize the
code. Here, we have a subprogram() function that calculates and prints the area of a
circle.
Canonical First Program
• • The following program is written in the C programming language:

• C is case sensitive. All commands in C must be lowercase.


• C has a free-form line structure. End of each statement must be marked with a
semicolon. Multiple statements can be on the same line. White space is
ignored.
• Statements can continue over many lines.
What main( ) returns?

main( ) should return 0 or 1.


• If it returns 0 to the operation system, the operating system will
understand that the program is successfully executed.
• If it returns 1, the operating system will understand that the program is
terminated with error.

Saurabh Bhattacharya, Assistant Professor, SCSE


• The purpose of the statement #include <stdio.h> is to allow the use of the printf
statement to provide program output. For each function built into the language, an
associated header file must be included. Text to be displayed by printf() must be
enclosed in double quotes.

• printf() is actually a function (procedure) in C that is used for printing variables


and text. Where text appears in double quotes "", it is printed without
modification.

• There are some exceptions however. This has to do with the \ and % characters.
These characters are modifiers, and for the present the \ followed by the n
character represents a newline character.
Escape sequences
•\n new line character
•\t horizontal tab
•\v vertical tab
•\a alarm
•\b backspace
•\” prints the double quote
•\’ prints the single quote.
•\\ prints the backslash character itself.
Format Specifiers Table

• The following table show what format specifiers should be used with what
data types:
OUTPUT & COMMENTS
• Thus the program prints
• Hello World!
And the cursor is set to the beginning of the next line. As we shall see later
on, what follows the \ character will determine what is printed (i.e., a tab,
clear screen, clear line, etc.)

• /* My first program */

• Comments can be inserted into C programs by bracketing text with the /* and
*/ delimiters. comments are useful for a variety of reasons.
• Primarily they serve as internal documentation for program structure
and functionality.
PROCESS OF COMPILING
&
RUNNING C PROGRAM
Compiling & Running A Program
Compiling & Running A Program - Explanation
• Write/Edit Source Code: The process starts with writing or editing the C source
code using an editor.The source code is written in plain text and saved with a .c
extension.
• Compile Source Code: The written source code is passed to the C Compiler, which
translates the high-level C code into object code (machine code).The compiler checks
for syntax errors in the code. Syntax errors occur if there is any mistake in the
language's grammar (e.g., missing semicolons or incorrect function names).
• Syntax Error Check: If syntax errors are found, the compiler provides error
messages, and the programmer needs to go back and fix the code. Once the errors are
corrected, the code is recompiled. If no syntax errors are found, the compilation
process continues to the next stage.
• Linker and Loader: The linker combines the object code with other code libraries
(from the System Library) that are required to create the final executable program.
The loader loads the program into memory so that it can be executed.
• Input Data: If the program requires input data, the input is provided at this stage. This
data is then used in the execution process.

• Execute Object Code: The object code is executed by the system. The program runs
using the provided input data.

• Logic/Data Error Check: During execution, if there are logic or data errors, the program
may not function as expected. These errors typically occur due to incorrect logic or
incorrect handling of input data. If errors occur, the program needs to be revised, and the
process may loop back to write/edit source code or further debugging.

• See Output: If there are no errors (syntax, logic, or data), the program successfully runs,
and the user can see the output.

• Error Loops-
• Syntax Errors: If syntax errors are encountered, the process loops back to the editing
stage.
• Logic Errors: If there are logic errors during execution, the process loops back to
correct the logic in the code.
Debugging: types of error
There are three basic errors:
❖Syntax/compilation error
❖Run-time exception error
❖logic error
🡪Syntax/compilation error
Error during compiling, prevents getting a compiled code. Modern compilers
indicate well the location of the error. Sometimes problems with delineators
such as semi-colons in C The difficulty is that compiler misses the error long
pass where the missing delineator is required.
🡪Run-time Exception error
When you get an error message while running the compiled code. such as C
seem to have only one type of error; Segmentation Fault,
🡺Logical Error:
Theses errors are the hardest to correct or detect. The program "runs" but the
output is not correct.
• Tools for Detecting and fixing logical error:
• Choose test cases well.
• Try to cover everything with small cases.
• Try one big case.
• Print intermediate value.

• Logical errors generally occur at:


• Loops:
Check the range of for loops, and the boolean expression of while loop
• Ifs:
Check complicated boolean expressions (more than one variables) and
especially if you are using negation
Type Conversion
• Type conversion refers to changing the data type of a variable from one
type to another. In C, type conversion is necessary when operations are
performed between different data types, or when a value of one type
needs to be assigned to a variable of another type.

• There are two types of type conversions in C:

Type Conversion

Implicit Type Explicit Type


Conversion (Automatic Conversion (Type
Type Conversion) Casting)
Implicit Type Conversion (Automatic Type
Conversion)
• Definition-
• When the C compiler automatically converts one data type to another
without programmer intervention, it is called implicit conversion.
• It happens when data types of variables in an expression differ.

• When it happens-
• In mixed-type expressions (e.g., adding int and float).
• When assigning a value of one type to a variable of another type.

• Promotion rules-
• In expressions involving different data types, the smaller data type is
promoted to the larger one (e.g., int to float, char to int).
• Example
• int x = 10;
• float y = 3.5;
• float result = x + y; // Here, `x` is automatically converted to `float`

• Conversion Hierarchy: The general hierarchy of data types in C is:


char → short → int → long → float → double → long double
Explicit Type Conversion (Type Casting)
• Definition-
• When the programmer explicitly forces a data type conversion, it is
called explicit type conversion or type casting.
• This is done manually by using the cast operator.

• Syntax-
• (new_data_type) expression;
• Example-
• int x = 5; float y = (float)x; // Here, `x` is explicitly cast to `float`

• Use Cases-
• When assigning a larger data type to a smaller data type (e.g., double to
int).When precision or behavior needs to be controlled explicitly in
mixed-type expressions.
• int a = 10, b = 3;
• float result;
• result = (float)a / b; // Here, `a` is cast to float to ensure floating-point
division
Data Loss in Type Conversion
•Implicit conversions can lead to loss of precision or data
truncation, especially when converting from a larger to a
smaller data type:
•Example:
•double d = 10.5;
•int i = d; // `i` will be 10, and the decimal part will be
lost.

•Explicit conversions (casting) help prevent unexpected results


by explicitly managing the conversion and handling any
potential data loss:
•Example:
•float f = 5.9;
•int i = (int)f; // `i` will be 5, with the fractional part
discarded.
Key Differences Between Implicit and Explicit
Conversion
Feature Implicit Conversion Explicit Conversion (Casting)

Automatic or Performed Performed manually by the


Manual automatically by the programmer
compiler
Syntax No special syntax Requires the use of casting
required operator
Control over Less control (happens Full control over conversion
Conversion according to rules) process

Risk of Data May lead to unintended Programmer can handle potential


Loss behavior issues

Example int a = 5; float b = a; float c = (float)5 / 2;


Operators and expressions

• Operators and expressions form the foundation for performing


calculations, making decisions, and manipulating data in C programs.

Operators

Arithmetic Relational Assignment Increment Special


Conditional
and
(Ternary)
Decrement

Logical Bitwise
Arithmetic Operators

•These operators perform basic arithmetic operations.


•+ (Addition)
•- (Subtraction)
•* (Multiplication)
•/ (Division)
•% (Modulus) – Returns the remainder of a division.

Example –
int a = 10, b = 5;
int sum = a + b; // sum = 15
int difference = a - b; // difference = 5
Relational Operators
•Used to compare two values and return a boolean result (true or
false).
• == (Equal to)
• != (Not equal to)
• > (Greater than)
• < (Less than)
Example –
• >= (Greater than or equal to) int x = 5, y = 10;
if (x < y)
• <= (Less than or equal to)
{
// True: x is less than y
}
Logical Operators

•Combine multiple relational expressions and return true or


false.
• && (Logical AND) – True if both operands are true.
• || (Logical OR) – True if at least one operand is true.
• ! (Logical NOT) – Reverses the truth value of an operand.

Example –
if (a > 5 && b < 10)
{
// True if both conditions are true
}
Assignment Operators
• Used to assign values to variables.
• = (Simple assignment)
• += (Add and assign)
• -= (Subtract and assign)
• *= (Multiply and assign)
• /= (Divide and assign)
• %= (Modulus and assign)

Example-
int c = 10;
c += 5; // c = c + 5, now c is 15

Note🡪 += short hand operator


Increment and Decrement Operators
• Used to increase or decrease the value of a variable by 1.
• ++ (Increment) – Adds 1 to the variable.
• -- (Decrement) – Subtracts 1 from the variable.

Example-
int a = 5;
a++; // Now a is 6
Bitwise Operators
• Operate on bits and perform bit-level operations.
• & (AND)
• | (OR)
• ^ (XOR)
• ~ (NOT)
• << (Left shift)
• >> (Right shift)
• : Operate on bits and perform bit-level operations.
Conditional (Ternary) Operator
• A shorthand for an if-else condition.

• ? : - Conditional Operator

Example –
int a = 10, b = 20;
int max = (a > b) ? a : b; // max will be 20
Special Operators
• Sizeof: Returns the size of a variable or data type in bytes.

• Example - int size = sizeof(int); // size = 4 (on most systems)

• & (Address-of): Returns the memory address of a variable

• Example - int a = 10; int *ptr = &a; // ptr holds the address of a

• * (Pointer Dereference): Accesses the value stored at the memory location


pointed by a pointer.
• Example -
• int a = 10;
• int *ptr = &a;
• printf("%d", *ptr); // Outputs 10
Managing Input and Output Operations
• In C programming, managing input and output (I/O) operations is
essential for interacting with the user or external systems.
• C provides a set of standard library functions to perform input and
output, which are defined in the stdio.h header file.
• These functions allow the program to read data (input) from standard
input devices (like a keyboard) and write data (output) to standard
output devices (like a screen).

• Standard Input/Output Devices:


• Standard Input: By default, this refers to the keyboard.
• Standard Output: By default, this refers to the screen (console).
• Standard I/O Streams:
• stdin: Standard input stream (usually the keyboard).
• stdout: Standard output stream (usually the console).
• stderr: Standard error stream (used for displaying error messages).
Types of I/O Operations
• Formatted Input/Output:
• Used when specific formatting is required for data entry or display. Commonly
uses scanf() for input and printf() for output.

• Character Input/Output:
• Deals with reading or writing single characters. Commonly uses getchar() and
putchar().

• String Input/Output:
• Used to handle strings (multiple characters). Functions like gets() (deprecated)
and puts() are used.

• File Input/Output:
• Used for reading from or writing to files stored on disk. Functions like fopen(),
fclose(), fscanf(), fprintf(), etc., are used for file operations.
Formatted Input/Output
• printf() Function (Formatted Output)
• The printf() function is used to print formatted output to the screen. It
allows the formatting of variables using format specifiers.
• Syntax- int printf(const char *format, ...);
• Format Specifiers:

%d: Integer %x: Hexadecimal


%f: Float %o: Octal
%c: Character %p: Pointer
%s: String

• scanf() Function (Formatted Input)


• The scanf() function is used to read formatted input from the user. It reads data
from standard input and stores it in variables.
Character Input/Output
• getchar() Function (Character Input)
• The getchar() function reads a single character from the keyboard.
• Syntax-
• int getchar(void);

• Example-
• char ch;
• printf("Enter a character: ");
• ch = getchar(); // Reads a character from the keyboard
• printf("You entered: %c\n", ch); // Outputs the character

• putchar() Function (Character Output)


• The putchar() function prints a single character to the console.
• Syntax:
• int putchar(int ch);

• Example
• char ch = 'A’;
• putchar(ch); // Outputs 'A' to the console
String Input/Output
• gets() and puts() (Deprecated)
• The gets() function reads an entire string (including spaces) until a
newline character is encountered.
• Note: gets() is deprecated due to security issues (buffer overflow). Use
fgets() instead.

• fgets() and fputs() (Safer String I/O)


• fgets() reads a string from the input stream (like stdin) safely by
specifying a buffer size.
• Syntax:
• char *fgets(char *str, int n, FILE *stream);

• Example
• char name[50];
• fgets(name, 50, stdin); // Reads up to 50 characters or until a
newline
• printf("You entered: %s", name);
File Input/Output
• File I/O in C allows reading from or writing to files stored on the disk.

• File Operations Overview:

• Opening a file: Use fopen() to open a file for reading or writing.

• Reading from a file: Use fscanf(), fgets(), or fread().

• Writing to a file: Use fprintf(), fputs(), or fwrite().

• Closing a file: Use fclose() to close an open file.

• File Modes:

• "r": Open a file for reading.

• "w": Open a file for writing (creates a new file or truncates an existing one).

• "a": Open a file for appending (writes data at the end).

• "r+": Open a file for both reading and writing.


• Buffering in Input/Output Operations-

• Buffering: C uses a mechanism called buffering for efficiency. When reading or writing
large amounts of data, the system collects data in a buffer (a temporary memory area)
before committing it to input or output devices.

• Flushing the buffer: Use fflush() to flush the output buffer and force the immediate
writing of buffered data to the output stream.

• Example:
• fflush(stdout); // Flush the output buffer to ensure immediate output
• Error Handling in Input/Output-

• Functions like fopen() return a NULL pointer if the file cannot be opened.

• You should always check the return value of functions like scanf() to detect input errors.

• Example:

FILE *file = fopen("nonexistent.txt", "r");


if (file == NULL)
{
printf("Error: Could not open file\n");
}

You might also like