Programming in c unit 5

12
Programming in C [BCA I Sem 2014] Unit V (1) BCA I Year Semester I PROGRAMMING IN C [BCA111] Unit V Introduction of strings, library functions of strings - strlen, strcpy, strcat, strcmp. File handling – file input/output statements, creating, reading, writing and modifying files. ===================================================================== »» File Handling A file is a place on the disk where a group of related data. When working with a standard data file (stream oriented data file), first of all a buffer area (the portion of main memory which can be directly accessed by the I/O devices) is established. The buffer area helps in fast read / write operation from/to the data file. C supports a number of functions to perform basic file operation. File naming Opening a file Reading data from a file Writing data from a file Closing a file The buffer area is associated by writing FILE *fptr; Here FILE (Use a uppercase letters only) is a special structure type defined within a system include file, namely stdio.h. *fptr is pointer variable Opening a file If we want to store data in a file in the secondary memory. A data file must be opened before it can be created or processed. The file name is associated with the buffer area or the stream. Syntax FILE *fptr;

Transcript of Programming in c unit 5

Page 1: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (1)

BCA I Year Semester I PROGRAMMING IN C

[BCA111]

Unit V Introduction of strings, library functions of strings - strlen, strcpy, strcat, strcmp. File handling – file input/output statements, creating, reading, writing and modifying files. ===================================================================== »» File Handling

A file is a place on the disk where a group of related data. When working

with a standard data file (stream oriented data file), first of all a buffer area (the portion of main memory which can be directly accessed by the I/O devices) is established. The buffer area helps in fast read / write operation from/to the data file.

C supports a number of functions to perform basic file operation.

• File naming • Opening a file • Reading data from a file • Writing data from a file • Closing a file

The buffer area is associated by writing

FILE *fptr; Here FILE (Use a uppercase letters only) is a special structure type defined within a system include file, namely stdio.h. *fptr is pointer variable Opening a file

If we want to store data in a file in the secondary memory. A data file must be opened before it can be created or processed. The file name is associated with the buffer area or the stream. Syntax

FILE *fptr;

Page 2: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (2)

• r open the file for reading only

fptr = fopen(“filename”, “mode”); Here file name represents the name of the data file and mode specifies

the purpose of opening the file. A file name may contain two parts, a primary name and an optional period with extension. Both the file name and mode are enclosed in double quotation marks.. File structure are already exists in an I/O library.

Mode are divided into three part

• w open the file for writing file • a open the file for appending data to it.

Note 1. If the mode is ‘reading’, and if it exists, then the file is opened with the current safe otherwise is an error occur. 2. If the mode is ‘writing’, a file with the specified name is created if the file does not exist the contents are deleted, if the file already exists. 3. If the mode is ‘appending’, a file is opened with the current content safe. A file with the specified name is created if the file does not exists Example

FILE *p1,*p2; p1= fopen(“data”,”r”); p2 = fopen(“result”,”w”);

Here the file data is opened for reading and result is opened for writing. If data file is exist then this file contents is safe. If data file is not exist then an error will occur. If result file is exist then this file contents is delete. If result file is not exist then the file is opened as a new file as a same name. Closing a file When the processing is over(reading/writing) in a file , it must be closed. The library function fclose() perform this task. Syntax

fclose( file pointer)

Example

Page 3: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (3)

fclose(fptr);

Input/ Output operation on files The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar functions and handle one character at a time. Syntax of getc and putc

putc(C, fptr); ch = getc(fptr);

The file pointer moves by one character position for every operation of getc and putc. The getc will return an end-of-file maker EOF, when end of the file has been reached. Therefore, the reading should be terminated when EOF is encountered. Example

#include<stdio.h> #include<conio.h> void main() {

FILE *fptr; char ch; printf("Data Input\n"); fptr = fopen("TEXT","w"); while((ch=getchar())!=EOF) {

putc(ch,fptr); } fclose(fptr); printf("Data Output\n"); fptr=fopen("TEXT","r"); while((ch=getc(fptr))!=EOF) {

printf("%c",ch);

Page 4: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (4)

} fclose(fptr); getch();

} Input Data Input Programming in C is fun We may be a successful programmer ^Z Data Output Programming in C is fun We may be a successful programmer The getw and putw functions The getw and putw functions are integer-oriented functions. They are similar to the getc and putc functions and are used to read and write integer values. These functions would be useful when we deal with only integer data. The general forms of getw and putw are: putw(int_var, fptr); getw(fptr); Example #include<stdio.h> #include<conio.h> void main() {

FILE *fptr; int x,y,z; clrscr(); fptr = fopen("INTEGER","w"); printf("Enter three integer number\n"); scanf("%d %d %d",&x,&y,&z); putw(x,fptr);

Page 5: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (5)

putw(y,fptr); putw(z,fptr); fclose(fptr); fptr = fopen("INTEGER","r"); printf("The three integer number is \n"); x=getw(fptr); y=getw(fptr); z=getw(fptr); printf("%d %d %d",x,y,z); fclose(fptr); getch();

} Output

Enter three integer number 1024 5263 789 The three integer number is 1024 5263 789

Random access to files

In the earlier programs the reading and writing in the file has been sequential in C, In C random access is achieved by using fseek(), ftell(), rewind() functions for manipulating the file pointers. It includes one or more of the following

• Insertion of a new item in the end of file • Deletion of an existing item • Modification of an existing item • Display a particular record or entire file contents

The fseek() function A read/write operation on a file results in shift in the current position on

the file. The current position on a file is the next byte position from where data will be read or written. The current position of the file is 1 i.e., at the beginning of the file. A current position beyond the last byte in the file under processing means end-of-file

Page 6: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (6)

Syntax of fseek()

fseek(fptr, offset, from_where); Here fptr is file pointer; offset is a variable of type long int that specifies

the number of bytes by which the file pointer is to be moved. From where is of type int and specifies the position on the file from where the offset would be effective

Value Meaning 0 Beginning of file 1 Current position 2 End of file

Example

fseek(fp,m,0) M byte forward move from beginning of file fseek(fp,+m,1) M byte forward move from current position of file fseek(fp,-m,2) M byte backward move from end of file of file If position is 2 then value of offset is negative bcoz forward move is not

possible after end of file, an error is occur.

The ftell() function This function takes a file pointer as a argument and return current

position of a file pointer from the file beginning.

Syntax of ftell() ftell(fptr); The value returned by ftell() is a long int and can be used by the fseek()

function for positioning the file pointer at the desired location.

Page 7: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (7)

Example #include<stdio.h> #include<conio.h> void main() {

FILE *fptr; long n; char c; clrscr(); fptr = fopen("RANDAM","w"); while((c=getchar())!=EOF) {

putc(c,fptr); } n= ftell(fptr); printf("No of character entered = %ld",n); fclose(fptr); getch();

} Output

abcd^Z No of character entered = 4 The rewind() function

It is used to reposition the current position to the beginning of a file. It is

useful for reinitializing the current position in a file.

Syntax of rewind() rewind(fptr);

Page 8: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (8)

Example #include<stdio.h> #include<conio.h> void main() {

FILE *fptr; long n; char c; clrscr(); fptr = fopen("RANDAM","w"); while((c=getchar())!=EOF)

putc(c,fptr); n= ftell(fptr); printf("No of character entered = %ld",n); fclose(fptr); getch();

} Output abcd^Z No of character entered = 0 The feof() function:- The feof() function can be test for an end of file condition. It takes a FILE pointer as its only argument and returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. It fp is a pointer to file that has just been opened for reading, then the statement Example

fp=fopen(“xyz”,”w”); feof(fp); if(feof(fp))

Page 9: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (9)

printf(“end of data”); The ferror() function:- The ferrorr function reports the status of the file indicated. It also takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing. If return zero otherwise. The statement

fp=fopen(“xyz”,”w”); feof(fp); if (ferror(fp) != o)

printf(“an error has occurred ”); We know that whenever a file is opened using fopen function, a file pointer is returned. If the file cannot be opened for some reason, then the function return a NULL pointer. This facility can be used to test whether a file has been opened or not. For example;

if (fp == NULL) printf(“file could not be opened”);

Page 10: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (10)

»» String/ Character Array These functions are defined in string.h header file. Hence you need to include this header file whenever you use these string handling functions in your program. All these functions take either character pointer or character arrays as arguments. The C language treats character strings, simply as array of character. The size in a character string represents the maximum number of character that the string can hold.

char name[15]; or char *name;

Here the ‘name’ as a character array variable that can be hold a maximum of 15 characters. We read the following string ‘LACHOO COLLEGE’ ‘L’ ‘A’ ‘C’ ‘H’ ‘O’ ‘O’ ‘C’ ‘O’ ‘L’ ‘L’ ‘E’ ‘G’ ‘E’ ‘\0’

When the compiler sees a character string, it terminates with an additional null character. The element name[15] holds the null character ‘\0’. When declaring character arrays, we must allow one extra element space for the null terminator. Following are some of the useful string handling functions supported by C. 1) strlen() 2) strcpy() 3) strcat() 4) strcmp() 5) strcmpi() strlen() strlen() function returns the length of the string. strlen() function returns integer value. Example: char *str = "Learn C Online";

NULL Character

Page 11: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (11)

int strLength; strLength = strlen(str); //strLength contains the length of the string i.e. 14

‘\0’ is not included in length. strcpy() strcpy() function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable. Syntax: strcpy(Destination_String,Source_String); Example: char *Destination_String; char *Source_String = "Learn C Online"; strcpy(Destination_String,Source_String); printf("%s", Destination_String); Output: Learn C Online strcat() strcat() is used to concatenate two strings. The Destination_String should be a variable and Source_String can either be a string constant or a variable.

Syntax: strcat(Destination_String, Source_String); Example: char *Destination_String ="Learn "; char *Source_String = "C Online"; strcat(Destination_String, Source_String); puts( Destination_String); Output: Learn C Online strcmp()

strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.

Page 12: Programming in c unit 5

Programming in C [BCA I Sem 2014] Unit V (12)

Syntax: int strcmp(string1, string2); This function returns integer value after comparison. Value returned is 0 if two strings are equal. If the first string is alphabetically greater than the second string then, it returns a positive value. If the first string is alphabetically less than the second string then, it returns a negative value Return value

• if Return value if < 0 then it indicates string1 is less than string2 • if Return value if > 0 then it indicates string2 is less than string1 • if Return value if = 0 then it indicates string1 is equal to string2

Example: char *string1 = "Learn C Online"; char *string2 = "Learn C Online"; int ret; ret=strcmp(string1, string2); printf("%d",ret); Output: 0 strcmpi() strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable. Syntax: int strcmpi(string1, string2); This function returns integer value after comparison. Example: char *string1 = “Learn C Online”; char *string2 = “LEARN C ONLINE”; int ret; ret=strcmpi(string1, string2); printf("%d",ret); Output: 0