0% found this document useful (0 votes)
8 views19 pages

Ivth Unit - Files in C

The document provides an overview of standard input/output functions in C programming, including getchar(), putchar(), gets(), and puts(). It explains formatted input/output functions such as printf() and scanf(), detailing their syntax, usage, and format specifiers for various data types. Additionally, it covers error handling, file access, and miscellaneous functions related to input and output operations.

Uploaded by

sriram98713
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)
8 views19 pages

Ivth Unit - Files in C

The document provides an overview of standard input/output functions in C programming, including getchar(), putchar(), gets(), and puts(). It explains formatted input/output functions such as printf() and scanf(), detailing their syntax, usage, and format specifiers for various data types. Additionally, it covers error handling, file access, and miscellaneous functions related to input and output operations.

Uploaded by

sriram98713
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/ 19

IV TH UNIT - Input and Output: Standard I/O, Formatted Output – printf, Formatted Input – scanf,

Variable length argument list, file access including FILE structure, fopen, stdin, sdtout and stderr,
Error Handling including exit, perror and error.h, Line I/O, related miscellaneous functions.

STANDARD I/O
The following library functions implement a simple model of text input and output.

The following 4 functions will be discussed here.


1.getchar()
2.putchar()
3.gets()
4.puts()

When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed it to
the program as per requirement. When we say Output, it means to display some data on screen, printer, or in
any file.

The standard Files


C programming treats all the devices as files. So devices such as the display are addressed in the same way as
files and the following three files are automatically opened when a program executes to provide access to the
keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose. This section explains how to
read values from the screen and how to print the result on the screen.

1.getchar()
This function is used to read a single character from the standard input (usually the keyboard). It waits for the
user to input a character and returns that character as an integer.
syntax:

int getchar(void);

getchar() function does not take any parameters. The input from the standard input is read as an unsigned char
and then it is typecast and returned as an integer value(int).

Example program - getchar()


#include <stdio.h>
int main()
{
int character;
character = getchar();
printf("The entered character is : %c", character);
return 0;
}
output
$
The entered character is : $
2.putchar():
This function is used to write a single character to the standard output (usually the console or terminal). It takes
a character as an argument and displays it. The character to be printed is fed into the function as an argument,
and if the writing is successful, the argument character is returned.

syntax

int putchar(int char);

Example program-putchar()
#include <stdio.h>
int main( )
{
char c;
printf( "Enter a character :");
c = getchar( );
printf("%c\n", c);
printf( "\nYou entered: ");
putchar(c);
return 0;
}
output
Enter a character :$
$
You entered: $

3.gets() function:
C library facilitates a special function to read a string from a user. This function is represented as gets() function
and is defined in the <stdio.h> header file of C. gets() function is used to read the string (sequence of characters)
from keyboard input. The function returns a pointer to the string where input is stored.

syntax

char *gets (char *string);

example program – gets()


#include <stdio.h>
#define MAX 15
int main()
{
// defining buffer
char buf[MAX];
printf("Enter a string: ");
// using gets to take string from stdin
gets(buf);
printf("string is: %s\n", buf);
return 0;
}

OUTPUT
Enter a string: WELCOME
string is: WELCOME

4.puts() function:
C library also facilitates a special function to print a string on the console screen. This function is represented as
puts() function and is also defined in the <stdio.h> header file of C. The return value of the puts function
depends on the success/failure of its execution. On success, the puts() function returns a non-negative value.
Otherwise, an End-Of-File (EOF) error is returned.
syntax

int puts(const char *string);

example program- puts()


// C program to illustrate the use of puts() function
#include <stdio.h>
int main()
{
// using puts to print hello world
char* str1 = "Hello world";
puts(str1);
puts("Welcome World");
return 0;
}
Output
Hello world
Welcome World
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

FORMATTED I/O FUNCTIONS-


Formatted Output – printf(), Formatted Input – scanf()
Formatted I/O functions are essential for handling user inputs and displaying outputs in a user-friendly way.
They enable programmers to:
1. Receive User Inputs: Formatted input functions help programs collect user input in a structured
manner. They use format specifiers to interpret and extract specific data types from user input.
2. Present Data to Users: Formatted output functions allow programs to present data to users in various
formats. Format specifiers are used to control how data is displayed, making it more readable and
visually appealing.
3. Support Multiple Data Types: These I/O functions are versatile and support a wide range of data
types, including integers, floating-point numbers, characters, and more. Each data type has
corresponding format specifiers for precise formatting.
4. Formatting Control: Programmers can use format specifiers to control the alignment, width,
precision, and other formatting aspects of displayed data, ensuring it’s presented as intended.

Why they are called Formatted I/0 Functions


These functions are called formatted I/O functions as they can use format specifiers in these functions.
Moreover, we can format these functions according to our needs. Here is the list of some specifiers.

no Format Specifier Type Description

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data


1.printf()
In C, printf() is a built-in function used to display values like numbers, characters, and strings on the console
screen. It’s pre-defined in the <stdio.h> header allowing easy output formatting in C programs.

Syntax

printf(“format specifier”, var1, var2, …., varn);

Example
#include <stdio.h>
int main()
{
int a;
a = 20;
printf("%d", a);
return 0;
}
Output
20

Example
#include <stdio.h>
int main()
{
// Displays the string written inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string

2. scanf():
In C, scanf() is a built-in function for reading user input from the keyboard. It can read values of various data
types like integers, floats, characters, and strings. scanf() is a pre-defined function declared in
the <stdio.h> header file. It uses the & (address-of operator) to store user input in the memory location of a
variable.
Syntax
scanf(“format specifier”, &var1, &var2, …., &varn);

Example-scanf()
#include <stdio.h>
int main()
{
int num1;
printf("Enter a integer number: ");
scanf("%d", &num1);
printf("You have entered %d", num1);
return 0;
}
Output
Enter a integer number: 56
You have entered 56
1.Output of integer numbers –printf()

The format specification for printing an integer number is : %wd


 Where w specifies the minimum field width for the output.
 However if the number is greater than the specified field, it will be printed in full, overriding the
minimum specification d specifies that the value to be printed is an integer.
 The number is written right-justified in the given field width. Leading blanks will appear as
necessary.
The following examples illustrate the output of the number 9876 under different formats.

 It is possible to force the printing to be left –justified by placing a minus sign directely after the %
character as shown in fourth example.
 It is also possible to pad with zeros the leading blanks by placing a 0 before the field width specifier
in the last item above.
 The minus(-) and zero(0) are known as flags. Long integers may be printed by specifying ld in the
place of d in the format specification. Similarly we may use hd for printing short integers.

example
#include<stdio.h>
void main(void)
{
int m=12345;
long n =987654;
printf("%d\n", m);
printf("%10d\n", m);
printf("%o10d\n", m);
printf("%-10d\n", m);
printf("%10ld\n", n);
printf("%10ld\n", -n);
}

output
12345
12345
3007110d
12345
987654
-987654
2.Output of real numbers-printf()
%w.pf
 integer w indicates the minimum number of positions that are to be used for the display of the value
and
 the integer p indicates the number of digits to be displayed after the decimal point.
 The value, when displayed, is rounded to p decimal places and printed right-justified in the field of
w column.
 Leading blanks and trailing zeros will appear as necessary. The default precision is 6 decimal places.
The negative numbers will be printed with minus sign.

following examples illustrate the output of the number y= 98.7654 under different formats
specifications.

Program
#include<stdio.h>
void main()
{
float y=98.7654;
printf("% 7.4f\n", y);
printf("%f\n",y);
printf("7.2f\n", y);
printf("-7.2f\n",y);
printf("07.2f\n",y);
printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n",y);
printf("%e\n",y);
}

Output
98.7654
98.765404
7.2f
-7.2f
07.2f

9.88e+01
-9.8765e+01
9.88e+01
9.876540e+01
3.printing of single character –printf()
A single character can be displayed in a desired position using the format :
%wc
 The character will be displayed right-justified in the field of w columns.
 We can make left-justified by placing a minus sign before the integer w.
 The default value for w is 1.

program
#include<stdio.h>
int main()
{
char a= 'c';
printf("Value of a is: %c", a);
return 0;
}
output
Value of a is: c

4.Printing of strings – printf()


 It is of the form %w.ps, where w specified the field width for display and
 p instructs that only the first p characters of the string are to be displayed. The display is right-
justified.

The following examples show the effect of variety of specifications in printing a string “NEW DELHI
110001” containing 16 characters including blanks.
scanf()
The general form of scanf()

scanf(“control string”, &arg1, &arg2, …. &argn);

The control sting specifies the field format in which the data is to be entered and the arguments arg1, arg2,
…,argn specify the address of locations where the data is stored. Control string and arguments are separated by
commas.

1.Inputting integer numbers- scanf()

The field specification for reading an integer number is : %wd


 The percentage sign % indicates that a conversion specification follows:
 w is an integer number that specifies the field width of the number to be read and
 d, known as the data character, indicates that the number to be read is in integer mode.

Consider the following example.

scanf(%2d %5d”, &num1, &num2);


input: 50 31426
the value 50 is assigned to num1 and 31426 to num2.
Suppose the input data is as follows : 31426 50 then the variable num1 will be assigned 31(because of %2d)
and num2 will be assigned 426. The value 50 that is unread will be assigned to the first variable in the next scanf
call.
That is the statement

Suppose the input data is as follows: 31426 50


scanf(“%d %d”, &num1, &num2)

will read data 31426 50 and


assigns num1=31426 and num2=50.

an input field may be skipped by specifying * in the place of field width. For example the statement
scanf(“%d %*d %d”, &a, &b) will assign the data 123 456 789 as follows:
123 to a , 456 skipped, 789 to b.
example
#include<stdio.h>
void main()
{
int a,b,c,x,y,z;
int p,q,r;
printf("enter 3 integer numbers \n");
scanf("%d %d %d",&a,&b,&c);
printf("%d %d %d \n\n", a,b,c);
printf("Enter two 4-digit numbers\n");
scanf("%4d %4d", &x, &y);
printf("%d %d", x, y);
printf("\n enter two integers\n");
scanf("%d %d", &a,&x);
printf("%d %d\n\n",a,x);
printf("enter a ten digit number \n");
scanf("%3d%4d%3d",&p,&q,&r);
printf("%d %d %d\n\n",p,q,r);}

Output
enter 3 integer numbers
34 56 78
34 56 78
Enter two 4-digit numbers
1234 5678
1234 5678
enter two integers
12 45
12 45
enter a ten digit number
1234567890
123 4567 890

2.Formatting floating Point Input-scanf()

%wf
Here w is an integer number specifying the maximum width of the input data including digits before and after
decimal points and the decimal itself. scanf() reads real number using the simple specifiation %f for both the
notations, namely decimal point notation and exponential notation.
For example the statement

case-1
scanf(“%f %f %f”, &x,&y, &z);
input: 475.89 43.21E-1 678
will assign the value 475.89 to x, 4.321 to y and 678.0 to z. A number may be skipped using %*f specification.

Case-2
When the length of the input data is less than the given width, then the values are stored correctly in the given
variables.
scanf("%3f%4f", &a, &b);
input: 4 1.2
output: 4.000000 1.200000
case-3
scanf("%3f%4f", &a, &b);
input: 1.2 33.1

In this case, the width and length of the input are same, so the values are stored correctly in the variables. i.e a =
1.2 and b = 33.1.

case-4
When the length of input data is greater than the width specified then the values are not stored correctly in the
variables.

scanf("%3f%4f", &a, &b);


Input: 5.21 983.71

As the width of the first variable is 3 only 5.2 is stored in the variable a while 1 is stored in b, and the rest of the
input is ignored.

case-5

printf("a=%4.2f, b=%4.2f", a, b);


input : a = 32.1 and b = 45.11.
Output: a=32.10, b=45.11

case-6
When the length of data is greater than the width specified, then the numbers are printed without any leading
spaces.
printf("a=%5.2f, b=%4.3f", a, b);
input : a = 34189.313 and b = 415.1411.
Output: a=34189.31, b=415.141

3.Inputting character strings-scanf()

We have seen how a single characer can be read from the terminal using getchar function. The same can be
achieved using scanf() function alsos. The scanf fucntion can input strings containing more than one character.

The specification is %ws or %wc.


char str[20];
scanf("%4s", str)

if the input = earning then output=earn in the variable str.

Program
#include<stdio.h>
main()
{
int no;
char name[15];
printf("enter serial number and name one\n");
scanf("%d %15s",&no,name);
printf("%d %15s \n\n", no, name);
}

Output
enter serial number and name one
34
welcome
34 welcome
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
FILE INPUT/OUTPUT IN C

Why do we need File Handling in C?

File handling in C stores data of our program in our local store, which can be used at any time because as the
execution of a program completes, our data is lost. Therefore, we need to save our data in any file form - text or
binary files

.We can perform tasks like opening, reading the existing file, writing or adding new content, creating a new file,
closing the file, or even saving the file to a certain location using C.

A few features of using files

 Reusability: Data stored in files can be used repeatedly.


 Portability: Files enable data transfer between different systems.
 Efficient: Quick access to stored data.
 Storage Capacity: Large amounts of data can be stored beyond the constraints of RAM.

Types of Files in C
We will be working with two types of files: -
1. Text file
2. Binary file

Let’s understand them in brief -

Text file - The user can create these files easily while handling files in C. It stores information in the form of
ASCII characters internally, and when the file is opened, the content is readable by humans. It can be created by
any text editor with a .txt or .rtf (rich text)extension. Since text files are simple, they can be edited by any text
editor like Microsoft Word, Notepad, Apple Text Edit, etc.

Binary file - It stores information in the form of 0’s or 1’s, and it is saved with the .bin extension, taking less
space. Since it is stored in a binary number system format, it is not readable by humans. Therefore it is more
secure than a text file.

C File Operations
There are different kinds of file operations in C.
1. Creating a new file
2. Opening an existing file
3. Writing data to a file
4. Reading data from an existing file.
5. Moving data to a specific location on the file
6. Closing the file

Functions for C File Operations

Now, we will be talking about different file-handling functions to perform file operations in C.

Function Description Syntax

Used to open an existing file or to


fopen() FILE *fopen(“file_name”, “mode”);
create a new file

fprintf() Used to write data in existing file fprintf(FILE *stream, const char *format [, argument, ...]);

fscanf() Used to read data from the file fscanf(FILE *stream, const char *format [, argument, ...]);
Function Description Syntax

fputc() Used to write characters in a file fputc(int c, FILE *stream);

fgetc() Used to read characters from a file fgetc(FILE *stream);

fclose() Used to close existing file fclose( FILE *fp );

File Pointer in C

When you want to perform file operations in C like reading from or writing to a file, you need a way to
reference that file within your program. This reference is provided by the file pointer. The file pointer stores the
address of a FILE structure, which contains details about the file, like its name, its current position, its size, etc.

Syntax of File Pointer:

FILE *pointer_name;
 FILE is a predefined data type in C, defined in the <stdio.h> header file. It represents a file type.
 * indicates that pointer_name is a pointer.
 pointer_name can be any valid variable name, and it will become the name of the file pointer.

For example, if you want to declare a file pointer named fptr, you'd write:

FILE *fptr;
fptr = fopen("filename.txt", "r"); //declaration of file pointer

This fptr can then be used with other functions to perform various operations on the file "filename.txt".

Open a File in C
In C, files are opened using the fopen() function. It's one of the fundamental functions for file handling in the C
language.

Syntax of fopen():

FILE *fptr;
fptr = fopen(filename, mode); //declaration of file pointer

Parameters:
 filename: A string that represents the name of the file to be opened. It can contain the full path or just
the file name if the file is in the current directory.
 mode: A string that specifies the mode in which the file should be opened. The mode can be read,
write, append, etc.

Return Value:
 If the file is successfully opened, the fopen() function returns a pointer to the file.
 If the file cannot be opened (for example, if the file does not exist or cannot be found), the function
returns a NULL pointer.

File opening modes in C:


Mode Description
Mode Description

r Opens a file for reading. The file must exist.

w Opens or creates a file for writing. If file exists, its contents are overwritten.

a Opens a file for appending. If file doesn't exist, it's created.

r+ Opens a file for both reading and writing. The file must exist.

w+ Opens a file for both reading and writing. It creates the file if it doesn't exist.

a+ Opens a file for both reading and appending. It creates the file if it doesn't exist.

rb Opens a binary file in reading mode.

wb Opens or creates a binary file in writing mode.

ab Opens a binary file in append mode.

rb+ Opens a binary file for both reading and writing.

wb+ Opens or creates a binary file for both reading and writing.

ab+ Opens a binary file for both reading and appending.

Closing a File :
syntax : int fclose(File *fp);

Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file.
This EOF is a constant defined in the header file stdio.h.

C Program to read a file


fgetc( ): This function reads the character from current pointer’s position and upon successful read moves the
pointer to next character in the file. Once the pointers reaches to the end of the file, this function returns EOF
(End of File). We have used EOF in our program to determine the end of the file.

#include <stdio.h>
void main()
{
FILE *fp; /* Pointer to the file */
char c;
fp= fopen ("C:\\myfiles\\newfile.txt", "r");
while(1) /* Infinite loop –use break to come out of the loop*/
{
c = fgetc(fp);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp);
return 0;
}

Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open a file in “r”
mode, you won’t be able to write the file as “r” is read only mode that only allows reading. This program asks
the user to enter a character and writes that character at the end of the file. If the file doesn’t exist then this
program will create a file with the specified name and writes the input character into the file.

#include <stdio.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("C:\\newfile.txt","w");
if(fp == NULL)
{
printf("Error");
exit(1);
}
printf("Enter any character: ");
scanf("%c", &ch);
/* You can also use fputc(ch, fp);*/
fprintf(fp,"%c",ch);
fclose(fp);
return 0;
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

FILE ACCESS
fprintf() & fscanf() in C programming
fprintf()- It is used to write content or string into a file instead of stdout console.
fscanf()- It is used to read content or string from a file pointed by a file pointer into the stream.

Syntax of fprintf() :

int fprintf(FILE *stream, const char *string, ...);

There are various parts of this syntax, they are mentioned below:
stream- It is used to point to the File object that helps to find the stream in which data is to be written.
format- It is used to write a string into the file pointed by the stream pointer.

Example program – fprintf()


#include<stdio.h>
int main (void)
{
FILE *fp;
fp = fopen(“sample.txt”, “w”);
fprintf(fp, “%s %s %d”, “Welcome”, “to”, 2023);
fclose(fp);
return 0;
}

Output:
The file sample text is open and contains “Welcome to 2023” in its file.

Syntax of fscanf() :
int fscanf(FILE *stream, const char *format, ...);

stream- Its is used to as the file pointer to point where the output will end.
format- Its is used as a string that contains various Format arguments.

Example:
#include<stdio.h>
main()
{
char b[255];
FILE *fp;
fp = fopen(“sample.txt”, “r”);
while(fscanf(fp, “%s”, b)!=EOF)
{
printf(“%s”, b );
}
fclose(fp);
}

Output:
Welcome to 2023

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

ERROR HANDLING IN C
C language does not provide any direct support for error handling. However a few methods and variables
defined in errno.h header file can be used to point out error using the return statement in a function. In C
language, a function returns -1 or NULL value in case of any error and a global variable errno is set with the
error code. So the return value can be used to check error while programming.

What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it. It is a global
variable, which can be used to identify which type of error was encountered while function execution, based on
its value. Below we have the list of Error numbers and what does they mean.

errno value Error


1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied

C language uses the following functions to represent error messages associated with errno:
 perror(): returns the string passed to it along with the textual represention of the current errno value.
 strerror() is defined in string.h library. This method returns a pointer to the string representation of
the current errno value.

//assume Error.txt file not existing


#include <stdio.h>
#include <errno.h>
#include <string.h>

int main ()
{
FILE *fp;
fp = fopen("Error.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
return 0;
}

output
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory

Other ways of Error Handling –exit()


What is exit() Function in C?
The exit function in c is defined under the stdlib.h header file is used to terminate the function currently running.
The function also terminates all the programs which are running, flushes all the file buffers, closes all the stream
and deletes all the temporary files.

 0 or EXIT_SUCCESS: The statements exit(EXIT_SUCCESS) and exit(0) mean that the program has
terminated successfully without any errors or interruptions.
 1 or EXIT_FAILURE: The statements exit(1) and exit(EXIT_FAILURE) mean that the program
terminated abruptly with an error.
EXAMPLE-1
#include <stdio.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("C:\\newfile.txt","w");

if(fp == NULL)
{
printf("Error");
exit(1);
}

printf("Enter any character: ");


scanf("%c",&ch);
fprintf(fp,"%c",ch);
fclose(fp);
return 0;
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
LINE INPUT AND OUTPUT
The standard library provides an input and output routine fgets that is similar to the getline function.

char *fgets(char *line, int maxline, FILE *fp);

fgets() reads the next input line (including the newline) from FILE *fp into the character array line; at most
maxline characters will be read. The resulting line is terminated with '\0'. Normally fgets() returns line; on end
of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means
end of file.)

For output, the function fputs() writes a string (which need not contain a newline) to a file:

int fputs(char *line, FILE *fp);

It returns EOF if an error occurs, and non-negative otherwise.

example-
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char chunk[128];
FILE *fp = fopen("file1.txt", "r");
if(fp == NULL)
{
perror("Unable to open file!");
exit(1);
}

while(fgets(chunk, sizeof(chunk), fp) != NULL)


{
fputs(chunk, stdout);
// marker string used to show where the content of the chunk array has ended
}

fclose(fp);
}

OUTPUT
Unable to open file!: No such file or directory

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

RELATED MISCELLANEOUS FUNCTIONS

The standard library provides a wide variety of functions. This section is a brief synopsis of the most useful.
More details and many other functions can be found in Appendix B.

String Operations
We have already mentioned the string functions strlen, strcpy, strcat, and strcmp, found in <string.h>. In the
following, s and t are char *'s, and c and n are ints.
strcat(s,t) concatenate t to end of s
strncat(s,t,n) concatenate n characters of t to end of s
strcmp(s,t) return negative, zero, or positive for s < t, s == t, s > t
strncmp(s,t,n) same as strcmp but only in first n characters
strcpy(s,t) copy t to s
strncpy(s,t,n) copy at most n characters of t to s
strlen(s) return length of s
strchr(s,c) find the first occurrence of a character c in a string s
strrchr(s,c) find the last occurrence of a character c in a string s

Character Class Testing and Conversion


Several functions from <ctype.h> perform character tests and conversions. In the following, c is an int that can
be represented as an unsigned char or EOF. The function returns int.

isalpha(c) non-zero if c is alphabetic, 0 if not


isupper(c) non-zero if c is upper case, 0 if not
islower(c) non-zero if c is lower case, 0 if not
isdigit(c) non-zero if c is digit, 0 if not
isalnum(c) non-zero if isalpha(c) or isdigit(c), 0 if not
isspace(c) non-zero if c is blank, tab, newline, return, formfeed, vertical tab
toupper(c) return c converted to upper case
tolower(c) return c converted to lower case

Ungetc
int ungetc(int c, FILE *fp)
pushes the character c back onto file fp, and returns either c, or EOF for an error.

Command Execution

system("date"); defined in stdlib.h // Sun Nov 26 04:12:30 PM UTC 2023

Storage Management
The functions malloc and calloc obtain blocks of memory dynamically.

void *malloc(size_t n)
returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.

void *calloc(size_t n, size_t size)


returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request
cannot be satisfied. The storage is initialized to zero.

Mathematical Functions
There are more than twenty mathematical functions declared in <math.h>; here are some of the more frequently
used. Each takes one or two double arguments and returns a double.
sin(x) sine of x, x in radians
cos(x) cosine of x, x in radians
exp(x) exponential function ex
log(x) natural (base e) logarithm of x (x>0)
log10(x) common (base 10) logarithm of x (x>0)
pow(x,y) xy
sqrt(x) square root of x (x>0)
fabs(x) absolute value of x

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
VARIABLE LENGTH ARGUMENTS
When we want to have a function, which can take variable number of arguments, i.e., parameters, instead of
predefined number of parameters. The C/C++ programming language provides a solution for this situation and
you are allowed to define a function which can accept variable number of parameters based on your
requirement.

The following example shows the definition of such a function.

int func(int, ... )


{
.
.
.
}
int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}

It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just
before the ellipses is always an int which will represent the total number variable arguments passed. To use such
functionality, you need to make use of <stdarg.h> header file which provides the functions and macros to
implement the functionality of variable arguments and follow the given steps −
 Define a function with its last parameter as ellipses and the one just before the ellipses is always an int
which will represent the number of arguments.
 Create a va_list type variable in the function definition. This type is defined in <stdarg.h> header file.
 Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro
va_start is defined in <stdarg.h> header file.
 Use va_arg macro and va_list variable to access each item in argument list.
 Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take the variable number of
parameters and return their average −

Example Program- Variable length arguments


#include <stdio.h>
#include <stdarg.h>
double average(int num,...)
{
va_list valist;
double sum = 0.0;
int i;
va_start(valist, num); //initialize valist for num number of arguments
for (i = 0; i < num; i++)
{
//access all the arguments assigned to valist
sum += va_arg(valist, int);
}
va_end(valist); //clean memory reserved for valist
return sum/num;
}

int main()
{
printf("Average of 2, 3, 4, 5 = %f”, average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f ", average(3, 5,10,15));
}
Output
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy