READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are available which is directly read a character or number of character from keyboard. In c language to read the input from the user, the getc( ) and getchar ( ) functions are used. getc( ): this function is used to read the character from a file stream, and return the character as an integer. Syntax int getc(file *stream); Where FILE * stream declares a file stream which is, a variable. The function returns the numeric value of the character read. If error occurs then function returns EOF. main( ) int ch; printf( Enter one character ); ch=getc(stdin); printf( the character entered is %c,ch); return 0; getchar( ) : this function is used to perform similar operation to getc( ). The getchar( ) function is equivalent to getc(stdin); This is a predefined function in C language which is available in stdio.h header file. Using this function we can read a single character from keyboard and store in character variable. When we want to read a number of character form keyboard the store all the data in a character array. Syntax int getchar(void); Where void indicates that has no arguments is needed for calling the function. 1
main( ) int ch1,ch2; printf( Enter two characters ); ch1=getc(stdin); ch2=getchar( ); printf( the fist character entered is : %c,ch1); printf( the Second character entered is : %c,ch2); return 0; putc( ): this function is a file handling function in C programming language which is used to write a character on standard output/screen. #include< stdio.h> int putc(int c, FILE *stream); Where the first argument, int c, indicates that the output is a character saved in an integer variable c, the second argument, File *stream, specifies a file stream. if successful, putc( ) returns the character written; otherwise, it returns EOF. main( ) int ch ch2=65; printf( the character that has numeric value of 65 is : ); putc(ch, stdout); return 0; putchar(): this function is a file handling function in C programming language which is used to write a character on standard output/screen. The only difference between the two functions is that putchar( ) needs only one argument to contain the character. There is need to specify the file stream, because the standard output (stdout) is the default file stream to putchar( ). 2
int putchar(int c); main( ) putchar(65); putchar(10); putchar(66); putchar(10); putchar(67); putchar(10); return 0; READING AND WRITING STRINGS gets( ) and puts( ) are used to read and write strings within the standard input and output stream. gets( ) : gets functions is used to read the string (sequence of characters) from keyboard input. Syntax char *gets(char *s); This is a predefined function in C language which is available in stdio.h header file. This function is used to read a single string from keyboard. Example: gets(string); Where the characters read from the standard input stream are stored in the character array identified by s. #include <stdio.h> int main( ) char str[100]; 3
printf( "Enter a value :"); gets( str ); printf( "\nyou entered: "); puts( str ); return 0; puts( ) : puts() function is used to write a line to the output screen or output stream. Syntax int puts (const char *s); Where s refers to character an array that contain a strings. The puts( ) function writes the string to the stdout. If the function is successful, it returns 0. Otherwise, a nonzero value is returned. The puts ( ) function appends a newline character to replace the null character at the end of a character array. #include <stdio.h> #include <string.h> int main() char string[40]; strcpy(str, "This is a test string"); puts(string); return 0; FORMATTED CONSOLE I/O printf() and scanf() functions comes under this category. They provide the flexibility to receive the input in some fixed format and to give the output in desired format. Formatted Console I/O functions are printf(), scanf() functions used to print and read formatted data of almost any type. Here the meaning of formatted is according to the requirement. printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default. These functions are declared and related macros are defined in stdio.h which is a header file in C language. 4
Here the printf() function is used to print the formatted data on to the monitor in a required format. It takes format string, list of operands as arguments and returns an integer. Note: Here in printf(), the meaning of print is to print and f is formatted syntax printf( control specifier,variable_list); Example program int main() int x; x=printf("hello world"); /* printing 11 bytes of data */ printf("\nprinted %d Bytes of data\n",x); return 0; Output Hello world Printed 11 Bytes of data. 5
scanf( ) : In C programming language, scanf() function is used to read character, string, numeric data from keyboard. it is a formatted input function used to accept almost any type of data from the console input device keyboard and store into specified variable (identifier) It takes format string, list of addresses of identifiers as arguments and returns an integer. Syntax scanf( control specifier, address of the variable); Example program #include <stdio.h> int main() char ch; char str[100]; printf("enter any character \n"); scanf("%c", &ch); printf("entered character is %c \n", ch); printf("enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("entered string is %s \n", str); KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF(): 1. printf() is used to display the output and scanf() is used to read the inputs. 2. printf() and scanf() functions are declared in stdio.h header file in C library. 3. All syntax in C language including printf() and scanf() functions are case sensitive. Format specifiers can be defined as the operators which are used in association with printf() function for printing the data that is referred by any object or any variable. When a value is stored within a particular variable then you cannot print the value stored in the variable straightforwardly without using the format specifiers. You can retrieve the data that are stored in the variables and can print them onto the console screen by implementing these format specifiers in a printf() function. 6
Format specifiers start with a percentage % operator and followed by a special character for identifying the type of the data. There are mostly several types of format specifiers that are available in C. List of format specifiers in C Format specifier Description %d Integer Format Specifier %f Float Format Specifier %c Character Format Specifier %s String Format Specifier %u Unsigned Integer Format Specifier %ld Long Int Format Specifier %g float or double format specifier %e float or double exponential format %O int unsigned octal value %P pointer address stored in pointer %X int unsigned hex value Standard C vs UNIX FILE I/O Input and output functions are process of copying the data between main memory and external devices. Input operation copies the data from input devices to main memory and output operation copies the data from memory to a device. C programming has several in-built library functions to perform input and output tasks. C was originally implemented for unix operating system. 7
Early versions of c support a set of I/O functions that are compatible with unix. This set of I/O functions is sometimes referred to as the UNIX-like I/O system. When c was standardized, the unix like functions were not incorporated into standard. Because they are redundant. The use of standard I/O functions has steadily risen and use of the unix-like functions has steadily decreased. Most programmers use the standard functions because they are potable to all environments. 8
FILES AND STREAMS File: file is a set of records that can be accessed through the set of library functions. Streams and File types: Stream means reading the data and writing the data. The streams are designed to allow the user to access the files efficiently. A stream is file or physical devices like keyboard, monitor, and printer. The file object uses these devices. The file object contains all the information about stream like current position, pointer to any buffer, error and EOF. File types There are two types of files Sequential file Random accesses file Sequential file: In this type record are kept sequentially. If we want read the last record of the file we need to read all the records before that record. It takes more time. For example if we desire to access the 10 th record then the first records should be read sequentially for reaching to 10 th record. Random access file: In this type record can be read and modified randomly. In this type if we want to read the last records of the file, we can read it directly. It takes less time as compared to sequential file. FILE SYSTEM BASICS There are different steps for file operations in c language. Opening a file Read a file Writing a file Closing a file A c language supports many more file handling functions that are available in standard library. A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. In C language, we use a structure pointer of file type to declare a file. 9
C provides a number of functions that helps to perform basic file operations. Following are the functions, Function fopen() fclose() getc() putc() fscanf() fprintf() getw() putw() fseek() ftell() rewind() description create a new file or open a existing file closes a file reads a character from a file writes a character to a file reads a set of data from a file writes a set of data to a file reads a integer from a file writes a integer to a file set the position to desire point gives current position in the file set the position to the beginning point Syntax FILE *fp; Opening a File or Creating a File The fopen() function is used to create a new file or to open an existing file. General Syntax : FILE *fp; fp = FILE *fopen(const char *filename, const char *mode); Or FILE *fp; fp = FILE *fopen( filename, mode ); 10
The fopen( ) functions are used to open a file to perform operations such as reading, writing, e.t.c. This function contains two arguments and returns pointer to file, if operation is successful otherwise it cannot be opened, the fopen ( ) returns a null. Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file. MODE: Mode refers to operation that will be performed on the file. File can be opened in basic 3 modes i.e reading mode, writing mode, appending mode. If file is not present on the specified path then new file can be created using write and append mode. Two types of streams Text streams : A text file stores data in the form of alphabets, digits and other special symbols by storing their ASCII values and are in a human readable format. For example, any file with a.txt,.c, etc extension. A small error in a textual file can be recognized and eliminated when seen. Binary streams : binary file contains a sequence or a collection of bytes which are not in a human readable format. For example, files with.exe,.mp3, etc extension. It represents custom data. a small error in a binary file corrupts the file and is not easy to detect. 11
Example program for read a file using fopen( ) function # include <stdio.h> int main( ) FILE *fp ; char data[50] ; printf( "\nopening the file test.txt in read mode\n" ) ; fp = fopen( "test2.txt", "r" ) ; if ( fp == NULL ) printf( "Could not open file test.txt" ) ; return 1; printf( "\n\n\nreading the file test.txt\n\n" ) ; while( fgets ( data, 50, fp )!= NULL ) printf( "%s", data ) ; printf("\n\n\nclosing the file test.txt") ; fclose(fp) ; return 0; CLOSING A FILE: fclose( ): The fclose() function is used to close an already opened file. General Syntax : int fclose( FILE *fp ); 12
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. Example program for writing a file using fopen( ) function # include <stdio.h> # include <string.h> int main( ) FILE *fp ; char data[50]; printf( "Opening the file test.txt in write mode\n" ) ; fp = fopen("test.txt", "w") ; // opening an existing file if ( fp == NULL ) printf( "Could not open file test.c" ) ; return 1; printf( "\n Enter some text from keyboard\n" ) ; while ( strlen ( gets( data ) ) > 0 ) // getting input from user fputs(data, fp) ; // writing in the file fputs("\n", fp) ; printf("\nclosing the file test.c\n") ; fclose(fp) ; // closing the file return 0; 13
Example program for Appending a file using fopen( ) function # include <stdio.h> # include <string.h> int main( ) FILE *fp ; char data[50]; printf( "Opening the file test.txt in append mode\n" ) ; fp = fopen("test.txt", "a") ; // opening an existing file if ( fp == NULL ) printf( "Could not open file test.c" ) ; return 1; printf( "\n Enter some text from keyboard\n" ) ; while ( strlen ( gets( data ) ) > 0 ) // getting input from user fputs(data, fp) ; // writing in the file fputs("\n", fp) ; printf("\nclosing the file test.c\n") ; fclose(fp) ; // closing the file return 0; Reading and Writing function in c 14
C language supports the fread( ) and fwrite( ) functions to reading the file and writing the file. fwrite() function: The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a structure. Syntax of fwrite() function fwrite( ptr, int size, int n, FILE *fp ); The fwrite() function takes four arguments. ptr : ptr is the reference of an array or a structure stored in memory. size : size is the total number of bytes to be written. n : n is number of times a record will be written. FILE* : FILE* is a file where the records will be written in binary mode. struct Student int roll; char name[25]; float marks; ; void main() FILE *fp; char ch; struct Student Stu; fp = fopen("student.dat","w"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); do printf("\nenter Roll : "); scanf("%d",&stu.roll); 15 printf("enter Name : "); scanf("%s",stu.name);
printf("enter Marks : "); scanf("%f",&stu.marks); fwrite(&stu,sizeof(stu),1,fp); printf("\ndo you want to add another data (y/n) : "); ch = getche(); while(ch=='y' ch=='y'); printf("\ndata written successfully..."); fclose(fp); Output Enter Roll : 1 Enter Name : Ashish Enter Marks : 78.53 Do you want to add another data (y/n) : n Data written successfully... fread() function: The fread() function is used to read bytes form the file. Syntax of fread() function fread( ptr, int size, int n, FILE *fp ); The fread() function takes four arguments. ptr : ptr is the reference of an array or a structure where data will be stored after reading. Size: size is the total number of bytes to be read from file. n : n is number of times a record will be read. FILE* : FILE* is a file where the records will be read. 16
Example of fread() function struct Student int roll; char name[25]; float marks; ; void main() FILE *fp; char ch; struct Student Stu; fp = fopen("student.dat","r"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\n\troll\tname\tmarks\n"); while(fread(&stu,sizeof(stu),1,fp)>0) printf("\n\t%d\t%s\t%f",stu.roll,stu.name,stu.marks); fclose(fp); Output Roll Name Marks 1 Ashish 78.53 17
FSEEK AND RANDOM ACCESS I/O The fseek() function is used to move the cursor in the file to the desired position. Syntax of fseek() function int fseek( FILE *fp, long offset, int pos ); The fseek() function takes three arguments, first is the file pointer, second is the offset that specifies the number of bytes to moved and third is the position from where the offset will move. It will return zero if successfully move to the specified position otherwise return nonzero value. There are three positions from where offset can move. #include<conio.h> void main( ) int n; FILE *fp; char ch; clrscr(); fp=fopen("file1.txt", "r"); if(fp==null) printf("file cannot be opened"); else printf("enter value of n to read last n characters"); scanf("%d",&n); fseek(fp,-n,2); 18
fclose(fp); getch(); while((ch=fgetc(fp))!=eof) printf("%c\t",ch); FTELL() FUNCTION IN C The ftell() function returns the current position of cursor in the file. Syntax of ftell() function ftell(file *fp); The ftell() function takes the file pointer as argument and return the current position in long type. Because of file may have more than 32767 bytes of data. The value is count from the beginning of the file. #include <stdio.h> #include <conio.h> void main () FILE *fp; int length; clrscr(); fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("size of file: %d bytes", length); getch(); rewind () : This function is used to move the file pointer to the beginning of the given file. In other words The rewind() function is used to move the cursor at the beginning of the file. we can also use fseek() function to move the cursor at the beginning of the file. 19
Syntax of rewind() function void rewind(file *fp); The rewind() function takes the file pointer as argument. void main() FILE *fp; char ch; fp = fopen("file.txt","a+"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\nwrite some data :\n"); while((ch=getchar())!=eof) //Statement 2 fputc(ch,fp); rewind(fp); //Statement 3 printf("\ndata in file :\n"); while((ch = fgetc(fp))!=eof) //Statement 4 printf("%c",ch); fclose(fp); Output : Write some data: Today is sunday. Data in file : Today is sunday. 20
In the above example, statement 1 will create a file named file.txt in read and append mode. Statement 1 is a loop, which is writing characters to the file. Statement 4 is an another loop for reading the data. If we ignore the 3 statement, 4 statement will not display any data because after writing data in the file, pointer will be at the EOF (end-fofile). To read the data we need to move the pointer to the begining of the file. The rewind() function in statement 3 will moving the pointer to the begining of the file. FPRINTF ( ) FSCANF ( ) FUNCTIONS IN C fprintf() function So far we have seen writing of characters, strings and integers in different files. This is not enough if we need to write characters, strings and integers in one single file, for that purpose we use fprintf() function. The fprintf() function is used to write mixed type in the file. Syntax of fprintf() function fprintf(file *fp,"format-string",var-list); The fprintf() function is similar to printf() function except the first argument which is a file pointer that specifies the file to be written. void main() FILE *fp; int roll; char name[25]; float marks; char ch; fp = fopen("file.txt","w"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); do printf("\nenter Roll : "); scanf("%d",&roll); 21
printf("\nenter Name : "); scanf("%s",name); printf("\nenter Marks : "); scanf("%f",&marks); fprintf(fp,"%d%s%f",roll,name,marks); printf("\ndo you want to add another data (y/n) : "); ch = getche(); while(ch=='y' ch=='y'); printf("\ndata written successfully..."); fclose(fp); Output : Enter Roll : 1 Enter Name : Kumar Enter Marks : 78.53 Do you want to add another data (y/n) : y Enter Roll : 2 Enter Name : Sumit Enter Marks : 89.62 Do you want to add another data (y/n) : n Data written successfully... fscanf() function The fscanf() function is used to read mixed type form the file. Syntax of fscanf() function fscanf(file *fp,"format-string",var-list); The fscanf() function is similar to scanf() function except the first argument which is a file pointer that specifies the file to be read. 22
void main() FILE *fp; char ch; fp = fopen("file.txt","r"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\ndata in file...\n"); while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=eof) //Statement 2 printf("\n%d\t%s\t%f",roll,name,marks); fclose(fp); Output : Data in file... 1 Kumar 78.53 2 Sumit 89.62 In the above example, Statement 1 will open an existing file file.txt in read mode and statement 2 will read all the data up to EOF(end-of-file) reached. THE STANDARD STREAMS Streams means reading and writing the records i.e sequence of bytes. Every runtime environment must provide three streams(such as stdin, stdout, stderr) viz standard input, standard output, standard error to every c-program. These streams are pointers to files. Streams are file or physical device such as key board, printer, monitor or screen. The streams are designed to allow the users to access the file efficiently. 23
File I/O Streams in C Programming Language : 1. In C all input and output is done with streams 2. Stream is nothing but the sequence of bytes of data 3. A sequence of bytes flowing into program is called input stream 4. A sequence of bytes flowing out of the program is called output stream 5. Use of Stream make I/O machine independent. Block diagram of standard streams 24
Standard Input Stream Device : 1. stdin stands for (Standard Input) 2. Keyboard is standard input device. 3. Standard input is data (Often Text) going into a program. 4. The program requests data transfers by use of the read operation. 5. Not all programs require input. Standard Output Stream Device : 1. stdout stands for (Standard Output) 2. Screen(Monitor) is standard output device. 3. Standard output is data (Often Text) going out from a program. 4. The program sends data to output device by using write operation. THE PREPROCESSOR DIRECTIVES # DEFINE AND #INCLUDE The preprocessor include the instructions for the compiler, these instructions are executed before the source code is compiled. Preprocessor directives begin with hash sign(#). No semicolon (;) is expected at the end of a preprocessor directive. This process is called preprocessing. In C programming language, preprocessor directive is a step performed before the actual source code compilation. It is not the part of compilation. Preprocessor directives in C programming language are used to define and replace tokens in the text and also used to insert the contents of other files into the source file. 25
Below is the list of preprocessor directives that C programming language offers. #define: #define is used to create symbolic constants (known as macros) in C programming language. This preprocessor command can also be used with parameterized macros. #define LESSTHAN < int main() int a = 30; if(a LESSTHAN 40) printf("a is Smaller"); return(0); 26
#include : #include is used to insert specific header file into C program. Advantages of pre-processor Programs becomes Readable and easy to understand. Easily modified or updated and efficient. 27