Rust LDN 24 7 19 Oxidising the Command LineMatt Provost
The document discusses various techniques for building command line utilities in Rust, including handling broken pipes, reading input byte-by-byte or line-by-line, reading from stdin or files, and handling non-UTF8 arguments. It provides code examples of reading from stdin, handling broken pipes gracefully, and collecting command line arguments as OsStrings to support non-UTF8 values. The document concludes by advertising open jobs at Yelp and providing contact information.
This document discusses input/output (I/O) stream classes in C++. It covers:
1. C++ uses stream classes like ifstream and ofstream to perform I/O operations with the console and files. These classes inherit from ios, istream, and ostream to provide input and output functionality.
2. Common stream operations include formatted I/O using operators like << and >>, and unformatted I/O using functions like get() and put().
3. The ios class and manipulators like setw(), setprecision(), and setfill() allow formatting of stream output, controlling aspects like field width, precision of floating point numbers, and character padding.
The document contains questions and explanations about C programming keywords and concepts like pointers, arrays, structures, unions, and bit manipulation. It provides definitions and examples for keywords like #define, #include, #pragma, #asm, #ifdef, and #endif. It also gives solutions to questions about pointers, counting bits to access specific bits or bytes of memory at a particular address, and explaining differences between array parameters and pointers in function definitions in C.
The document discusses various topics related to C language including:
- Benefits and features of C like low-level operations, structured programming, and modular programming
- Data types in C like fundamental types (char, int, float), derived types, and defining variables
- Structure of C functions including single-level and multiple-level functions
- Input-output functions in C like character-based (getc, putc), string-based (gets, puts)
C is a procedural programming language commonly used for system and application development. It uses functions and globally visible variables. Functions are declared before use. The main() function is the program entry point. Programs are compiled and linked separately. The C preprocessor handles includes and macros. Functions are defined with declarations and definitions. Control structures like if/else and loops are similar to other languages. Standard input/output functions handle file and terminal I/O. Formatted printing and scanning uses format specifiers. Type conversions must be explicitly cast.
This document provides an introduction and overview of the C programming language. It covers basic C concepts like data types, variables, operators, input/output, control flow, functions and pointers. It also compares C to Java and discusses similarities and differences between the two languages. The document is intended to teach basic C programming concepts.
This document provides an introduction to the C programming language. It covers basic C fundamentals like data types, variables, operators, input/output functions, control flow statements, and functions. It also compares C to Java and discusses similarities and differences between the two languages. The document is intended to teach basic C concepts to beginner programmers.
The document provides an overview of the C programming language. It states that C was developed in 1972 by Dennis Ritchie at Bell Labs and was used to develop the UNIX operating system. The document then covers various features of C like it being a mid-level programming language, having structured programming, pointers, loops, functions, arrays, and more. It provides examples to explain concepts like input/output functions, data types, operators, control structures, and pointers.
Fundamentals of Programming Constructs.pptxvijayapraba1
The algorithm involves taking Celsius temperature as input, multiplying it by 1.8 and adding 32 to convert it to Fahrenheit. This is implemented in a C program that takes Celsius input, performs the conversion calculation and prints the Fahrenheit output.
The document discusses input and output in C programming. It covers:
1) The stdin, stdout, and stderr devices that are automatically opened for input/output and some common I/O library functions that use these devices.
2) The printf function for formatted output to stdout, including format specifiers and examples.
3) The scanf function for formatted input from stdin using a similar format specifier syntax as printf. It also discusses getting input from files using redirection.
C is a low-level programming language suitable for systems programming. It is small but powerful, with a large collection of data types and operators. It assumes the programmer knows what they are doing and does not mandate extensive error checking. The document discusses the basics of C including data types, operators, input/output, expressions, selection statements, loops, functions, and pointers. It provides examples of basic C programs and comparisons between C and Java.
C programming basics are covered including:
1. Introduction to C including strengths, weaknesses and similarities/differences to Java
2. Basic data types, variables, and type conversions
3. Input/output using printf and scanf formatted functions
4. Operators, expressions, conditional expressions, and control flow
5. Examples include a Celsius to Fahrenheit conversion table printed in various ways
The document provides a quick introduction to C programming, covering topics like functions, variables, memory, expressions, and recursion. It uses a recursive pow() function to demonstrate recursion and the call stack. Each function call gets its own copy of arguments and local variables, stored on the call stack.
This document provides a quick introduction to the C programming language. It discusses basic C syntax like main functions, header files, comments, and variables. It also covers data types, memory, functions, scopes, expressions, control flow statements like if/else and loops. Functions can access arguments and global variables from their own scope but not variables from outer scopes unless passing their addresses.
The document provides a quick introduction to C programming. It discusses some key concepts in C including functions, variables, memory, data types, expressions and evaluation, and recursion. It provides an example of a recursive pow() function to calculate powers and discusses how function calls are handled through the stack.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
This document provides information on various data types in C programming language including integer, float, character and their properties. It discusses the size of basic data types using sizeof operator and size_t type. It also demonstrates the use of format specifiers in printf() statement to print values of different types and handles overflow, underflow cases. Code snippets are included to illustrate concepts around variable declaration, initialization, input-output using scanf() and printf().
Input refers to accepting data while output refers to presenting data. Normally the data is accepted from keyboard and is outputted onto the screen.
C language has a series of standard input-output (I/O) functions. Such I/O functions together form a library named stdio.h. Irrespective of the version of C language, user will have access to all such library functions. These library functions are classified into three broad categories.
a) Console I/O functions : Functions which accept input from keyboard and produce output on the screen.
b) Disk I/O functions : Functions which perform I/O operations on secondary storage devices like floppy disks or hard disks.
c) Port I/O functions : Functions which perform I/O operations on various ports like printer port, mouse port, etc.
Console I/
This document provides an overview of the Go programming language. It discusses that Go was initially developed at Google in 2007 and is now an open source language used by many companies. The document then covers Why Go is useful, including its memory management, concurrency support, and cross-platform capabilities. It also summarizes some of Go's basic syntax like packages, functions, variables, types, and control structures. Finally, it discusses some key Go concepts like methods, interfaces, channels, and the net/http package.
This document provides an overview of the C programming language. It discusses basics like data types, operators, input/output functions, and compiling and running C code. It also gives examples of simple C programs and explains concepts like operator precedence and type casting. The document is a lecture on C programming with 19 sections covering topics from writing C code to homework problems involving increment operators.
- Go is a programming language created at Google. It is fast, statically typed, and has garbage collection.
- The tutorial covers Go's history, why it was created, library support, and provides examples of variables, functions, flow control, methods, interfaces, and goroutines.
- The document includes an outline, code examples throughout to demonstrate the concepts, and references additional resources for learning Go.
This document summarizes key concepts in C programming including file handling, structures, and dynamic memory allocation. It discusses opening, reading from, and writing to files. It also describes defining custom data types using structures and typedef, accessing parts of structures, and passing structures to functions. Finally, it covers dynamically allocating memory at runtime using malloc to allow for variable-sized arrays, and the importance of checking for errors and freeing allocated memory.
C was created in the early 1970s at Bell Labs by Dennis Ritchie. It is commonly used for systems programming like operating systems and compilers. C code is compiled into efficient, portable machine code. A C program structure includes preprocessor commands, functions, variables, statements/expressions, and comments. Key C language elements are keywords, identifiers, constants, comments, and symbols. C supports various data types like int, char, float, and double that determine memory usage and value representation. Variables must be declared with a specific data type before use.
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
Fantom is an object-oriented and functional programming language that runs on the JVM, CLR and JavaScript engines. It features type inference, literals, functions, closures, mixins, and support for Java and JavaScript interoperability. Fantom has a built-in modular system and declarative build tools. It aims to balance static and dynamic typing with safety features like null safety and immutable/constant types and data structures.
The document provides an overview of the C programming language. It states that C was developed in 1972 by Dennis Ritchie at Bell Labs and was used to develop the UNIX operating system. The document then covers various features of C like it being a mid-level programming language, having structured programming, pointers, loops, functions, arrays, and more. It provides examples to explain concepts like input/output functions, data types, operators, control structures, and pointers.
Fundamentals of Programming Constructs.pptxvijayapraba1
The algorithm involves taking Celsius temperature as input, multiplying it by 1.8 and adding 32 to convert it to Fahrenheit. This is implemented in a C program that takes Celsius input, performs the conversion calculation and prints the Fahrenheit output.
The document discusses input and output in C programming. It covers:
1) The stdin, stdout, and stderr devices that are automatically opened for input/output and some common I/O library functions that use these devices.
2) The printf function for formatted output to stdout, including format specifiers and examples.
3) The scanf function for formatted input from stdin using a similar format specifier syntax as printf. It also discusses getting input from files using redirection.
C is a low-level programming language suitable for systems programming. It is small but powerful, with a large collection of data types and operators. It assumes the programmer knows what they are doing and does not mandate extensive error checking. The document discusses the basics of C including data types, operators, input/output, expressions, selection statements, loops, functions, and pointers. It provides examples of basic C programs and comparisons between C and Java.
C programming basics are covered including:
1. Introduction to C including strengths, weaknesses and similarities/differences to Java
2. Basic data types, variables, and type conversions
3. Input/output using printf and scanf formatted functions
4. Operators, expressions, conditional expressions, and control flow
5. Examples include a Celsius to Fahrenheit conversion table printed in various ways
The document provides a quick introduction to C programming, covering topics like functions, variables, memory, expressions, and recursion. It uses a recursive pow() function to demonstrate recursion and the call stack. Each function call gets its own copy of arguments and local variables, stored on the call stack.
This document provides a quick introduction to the C programming language. It discusses basic C syntax like main functions, header files, comments, and variables. It also covers data types, memory, functions, scopes, expressions, control flow statements like if/else and loops. Functions can access arguments and global variables from their own scope but not variables from outer scopes unless passing their addresses.
The document provides a quick introduction to C programming. It discusses some key concepts in C including functions, variables, memory, data types, expressions and evaluation, and recursion. It provides an example of a recursive pow() function to calculate powers and discusses how function calls are handled through the stack.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
This document provides information on various data types in C programming language including integer, float, character and their properties. It discusses the size of basic data types using sizeof operator and size_t type. It also demonstrates the use of format specifiers in printf() statement to print values of different types and handles overflow, underflow cases. Code snippets are included to illustrate concepts around variable declaration, initialization, input-output using scanf() and printf().
Input refers to accepting data while output refers to presenting data. Normally the data is accepted from keyboard and is outputted onto the screen.
C language has a series of standard input-output (I/O) functions. Such I/O functions together form a library named stdio.h. Irrespective of the version of C language, user will have access to all such library functions. These library functions are classified into three broad categories.
a) Console I/O functions : Functions which accept input from keyboard and produce output on the screen.
b) Disk I/O functions : Functions which perform I/O operations on secondary storage devices like floppy disks or hard disks.
c) Port I/O functions : Functions which perform I/O operations on various ports like printer port, mouse port, etc.
Console I/
This document provides an overview of the Go programming language. It discusses that Go was initially developed at Google in 2007 and is now an open source language used by many companies. The document then covers Why Go is useful, including its memory management, concurrency support, and cross-platform capabilities. It also summarizes some of Go's basic syntax like packages, functions, variables, types, and control structures. Finally, it discusses some key Go concepts like methods, interfaces, channels, and the net/http package.
This document provides an overview of the C programming language. It discusses basics like data types, operators, input/output functions, and compiling and running C code. It also gives examples of simple C programs and explains concepts like operator precedence and type casting. The document is a lecture on C programming with 19 sections covering topics from writing C code to homework problems involving increment operators.
- Go is a programming language created at Google. It is fast, statically typed, and has garbage collection.
- The tutorial covers Go's history, why it was created, library support, and provides examples of variables, functions, flow control, methods, interfaces, and goroutines.
- The document includes an outline, code examples throughout to demonstrate the concepts, and references additional resources for learning Go.
This document summarizes key concepts in C programming including file handling, structures, and dynamic memory allocation. It discusses opening, reading from, and writing to files. It also describes defining custom data types using structures and typedef, accessing parts of structures, and passing structures to functions. Finally, it covers dynamically allocating memory at runtime using malloc to allow for variable-sized arrays, and the importance of checking for errors and freeing allocated memory.
C was created in the early 1970s at Bell Labs by Dennis Ritchie. It is commonly used for systems programming like operating systems and compilers. C code is compiled into efficient, portable machine code. A C program structure includes preprocessor commands, functions, variables, statements/expressions, and comments. Key C language elements are keywords, identifiers, constants, comments, and symbols. C supports various data types like int, char, float, and double that determine memory usage and value representation. Variables must be declared with a specific data type before use.
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
Fantom is an object-oriented and functional programming language that runs on the JVM, CLR and JavaScript engines. It features type inference, literals, functions, closures, mixins, and support for Java and JavaScript interoperability. Fantom has a built-in modular system and declarative build tools. It aims to balance static and dynamic typing with safety features like null safety and immutable/constant types and data structures.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
How to use nRF24L01 module with ArduinoCircuitDigest
Learn how to wirelessly transmit sensor data using nRF24L01 and Arduino Uno. A simple project demonstrating real-time communication with DHT11 and OLED display.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
The role of the lexical analyzer
Specification of tokens
Finite state machines
From a regular expressions to an NFA
Convert NFA to DFA
Transforming grammars and regular expressions
Transforming automata to grammars
Language for specifying lexical analyzers
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
Ad
Lecture 04 Programming C for Beginners 001
1. 6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
1
2. Blocks
• Blocks combine multiple statements into a single unit.
• Can be used when a single statement is expected.
• Creates a local scope (variables declared inside are local
to the block).
• Blocks can be nested.
{
in t x =0;
{
int y=0; / ∗ both x and y v i s i b l e ∗ /
}
/ ∗ only x v i s i b l e ∗ /
}
1
3. Conditional blocks
if ... else..else if is used for conditional branching of execution
i f ( cond )
{
/ ∗ code executed i f cond i s tru e ∗ /
}
else
{
/ ∗ code executed i f cond i s fa l s e ∗ /
}
2
4. Conditional blocks
switch..case is used to test multiple conditions (more efficient
than if else ladders).
switch ( opt )
{
case ’A’ :
/ ∗ execute i f opt == ’A ’ ∗ /
break ;
case ’B’ :
case ’C’ :
/ ∗ execute i f opt == ’B ’ | | opt == ’C ’ ∗ /
default :
}
3
5. Iterative blocks
• while loop tests condition before execution of the block.
• do..while loop tests condition after execution of the block.
• for loop provides initialization, testing and iteration together.
4
6. 6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
5
7. goto
• goto allows you to jump unconditionally to arbitrary part of
your code (within the same function).
• the location is identified using a label.
• a label is a named location in the code. It has the same
form as a variable followed by a ’:’
s t a r t :
{
i f ( cond )
goto outside ;
/ ∗ some code ∗ /
goto s t a r t ;
}
outside :
/ ∗ outside block ∗ /
5
8. Spaghetti code
Dijkstra. Go To Statement Considered Harmful.
Communications of the ACM 11(3),1968
• Excess use of goto creates sphagetti code.
• Using goto makes code harder to read and debug.
• Any code that uses goto can be written without using one.
6
9. error handling
Language like C++ and Java provide exception mechanism to
recover from errors. In C, goto provides a convenient way to exit
from nested blocks.
cont _flag =1;
for ( . . )
for ( . . ) {
{ for ( i n i t ; c o n t _ f l a g ; i t e r )
for ( . . ) {
{ i f ( error_cond )
i f ( error_cond ) {
goto e r r o r ; c o n t _ f l a g =0;
/ ∗ skips 2 blocks ∗ / break ;
} }
} / ∗ i n n er loop ∗ /
e r r o r : }
i f ( ! c o n t _ f l a g ) break ;
/ ∗ outer loop ∗ /
}
7
10. 6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
8
11. Preliminaries
• Input and output facilities are provided by the standard
library <stdio.h> and not by the language itself.
• A text stream consists of a series of lines ending with ’n’.
The standard library takes care of conversion from
’rn’−’n’
• A binary stream consists of a series of raw bytes.
• The streams provided by standard library are buffered.
8
12. Standard input and output
int putchar(int)
• putchar(c) puts the character c on the standard output.
• it returns the character printed or EOF on error.
int getchar()
• returns the next character from standard input.
• it returns EOF on error.
9
13. Standard input and output
What does the following code do?
int main ( )
{
char c ;
while ( ( c=getchar ( ) ) ! = EOF)
{
i f ( c>=’A’ && c<=’Z’ )
c=c−’A’+’a’ ;
putchar ( c ) ;
}
return 0;
}
To use a file instead of standard input, use ’<’ operator (*nix).
• Normal invocation: ./a.out
• Input redirection: a.out < file.txt. Treats file.txt as source of
standard input.This is an OS feature, not a language
feature.
10
14. Standard output:formatted
int printf (char format[],arg1,arg2 ,...)
• printf() can be used for formatted output.
• It takes in a variable number of arguments.
• It returns the number of characters printed.
• The format can contain literal strings as well as format
specifiers (starts with %).
Examples:
p r i n t f ( "hello worldn" ) ;
p r i n t f ( "%dn" ,10); / ∗ format : %d ( intege r ) , argument :10 ∗ /
p r i n t f ( "Prices:%d and %dn" ,10 ,20);
11
15. printf format specification
The format specification has the following components
%[flags][width ][. precision ][ length]<type>
type:
type meaning example
d,i integer printf ("%d",10); /∗prints 10∗/
x,X integer (hex) printf ("%x",10); /∗print 0xa∗/
u unsigned integer printf ("%u",10); /∗prints 10∗/
c character printf ("%c",’A’); /∗prints A∗/
s string printf ("%s","hello"); /∗prints hello∗/
f float printf ("%f",2.3); /∗ prints 2.3∗/
d double printf ("%d",2.3); /∗ prints 2.3∗/
e,E float(exp) 1e3,1.2E3,1E−3
% literal % printf ("%d %%",10); /∗prints 10%∗/
12
18. printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
precision:
format output
printf ("%.2f,%.0f,1.141,1.141) 1.14,1
printf ("%.2e,%.0e,1.141,100.00) 1.14e+00,1e+02
printf ("%.4s","hello") hell
printf ("%.1s","hello") h
15
19. printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
modifier:
modifier meaning
h interpreted as short. Use with i,d,o,u,x
l interpreted as long. Use with i,d,o,u,x
L interpreted as double. Use with e,f,g
16
20. Digression: character arrays
Since we will be reading and writing strings, here is a brief
digression
• strings are represented as an array of characters
• C does not restrict the length of the string. The end of the
string is specified using 0.
For instance, "hello" is represented using the array
{’h’,’e’,’l’,’l’,’0’}.
Declaration examples:
• char str []="hello"; /∗compiler takes care of size∗/
• char str[10]="hello"; /∗make sure the array is large enough∗/
• char str []={ ’h’,’e’,’l’,’l’,0};
Note: use " if you want the string to contain ".
17
21. Digression: character arrays
Comparing strings: the header file <string.h> provides the
function int strcmp(char s[],char t []) that compares two strings in
dictionary order (lower case letters come after capital case).
• the function returns a value <0 if s comes before t
• the function return a value 0 if s is the same as t
• the function return a value >0 if s comes after t
• strcmp is case sensitive
Examples
• strcmp("A","a") /∗<0∗/
• strcmp("IRONMAN","BATMAN") /∗>0∗/
• strcmp("aA","aA") /∗==0∗/
• strcmp("aA","a") /∗>0∗/
18
22. Formatted input
int scanf(char∗ format ,...) is the input analog of printf.
• scanf reads characters from standard input, interpreting
them according to format specification
• Similar to printf , scanf also takes variable number of
arguments.
• The format specification is the same as that for printf
• When multiple items are to be read, each item is assumed
to be separated by white space.
• It returns the number of items read or EOF.
• Important: scanf ignores white spaces.
• Important: Arguments have to be address of variables
(pointers).
19
23. Formatted input
int scanf(char∗ format ,...) is the input analog of printf.
Examples:
printf ("%d",x) scanf("%d",&x)
printf ("%10d",x) scanf("%d",&x)
printf ("%f",f) scanf("%f",&f)
printf ("%s",str) scanf("%s",str) /∗note no & required∗/
printf ("%s",str) scanf("%20s",str) /∗note no & required∗/
printf ("%s %s",fname,lname) scanf("%20s %20s",fname,lname)
20
24. String input/output
Instead of writing to the standard output, the formatted data can
be written to or read from character arrays.
int sprintf (char string [], char format[],arg1,arg2)
• The format specification is the same as printf.
• The output is written to string (does not check size).
• Returns the number of character written or negative value
on error.
int sscanf(char str [], char format[],arg1,arg2)
• The format specification is the same as scanf;
• The input is read from str variable.
• Returns the number of items read or negative value on
error.
21
25. File I/O
So far, we have read from the standard input and written to the
standard output. C allows us to read data from text/binary files
using fopen().
FILE∗ fopen(char name[],char mode[])
• mode can be "r" (read only),"w" (write only),"a" (append)
among other options. "b" can be appended for binary files.
• fopen returns a pointer to the file stream if it exists or
NULL otherwise.
• We don’t need to know the details of the FILE data type.
• Important: The standard input and output are also FILE*
datatypes (stdin,stdout).
• Important: stderr corresponds to standard error
output(different from stdout).
22
26. File I/O(cont.)
int fclose(FILE∗ fp)
• closes the stream (releases OS resources).
• fclose() is automatically called on all open files when
program terminates.
23
27. File input
int getc(FILE∗ fp)
• reads a single character from the stream.
• returns the character read or EOF on error/end of file.
Note: getchar simply uses the standard input to read a
character. We can implement it as follows:
#define getchar() getc(stdin)
char[] fgets(char line [], int maxlen,FILE∗ fp)
• reads a single line (upto maxlen characters) from the input
stream (including linebreak).
• returns a pointer to the character array that stores the line
(read-only)
• return NULL if end of stream.
24
28. File output
int putc(int c,FILE∗ fp)
• writes a single character c to the output stream.
• returns the character written or EOF on error.
Note: putchar simply uses the standard output to write a
character. We can implement it as follows:
#define putchar(c) putc(c,stdout)
int fputs(char line [], FILE∗ fp)
• writes a single line to the output stream.
• returns zero on success, EOF otherwise.
int fscanf(FILE∗ fp,char format[],arg1,arg2)
• similar to scanf,sscanf
• reads items from input stream fp.
25
29. Command line input
• In addition to taking input from standard input and files, you
can also pass input while invoking the program.
• Command line parameters are very common in *nix
environment.
• So far, we have used int main() as to invoke the main
function. However, main function can take arguments that
are populated when the program is invoked.
26
30. Command line input (cont.)
int main(int argc,char∗ argv[])
• argc: count of arguments.
• argv[]: an array of pointers to each of the arguments
• note: the arguments include the name of the program as
well.
Examples:
• ./cat a.txt b.txt (argc=3,argv[0]="cat" argv[1]="a.txt"
argv[2]="b.txt"
• ./cat (argc=1,argv[0]="cat")
27