You are on page 1of 24

strcat() - This function is used for concatenation of two strings.

If first string is
"King" and second string is “size” then after using this function the first string
becomes "Kingsize”

#include<stdio.h>
#include<string.h>
main( )
char strl[20],str2[20];
printf ("Enter the first string ") ;
scanf("%s",strl); ,
printf ("Enter the second string ") ;
scanf("%s",str2) ;
strcat(strl,str2); .
printt'( "First string %s \ tSecond string %s\n", strl, str2) ;
Without using function
*astrcat(char strl[ ),char str2[ ])
{
int i=0,j=0;
while(strl[i] !='\0')
i++;
while(str2[j]!='\0') \\Add second string at the end of first
{
strl[i]=str2[j] ;
i++;
j ++;
}
str1[i]='\0' ;
return' str1;
}
Program to test whether a word is palindrome or not
#include<stdio.h> flag=0;
#include<string.h> break;
main( ) i++;
{ j - -;
char str[10]; }
int i=O,j,flag; if (flag==l)
printf ("Enter the word ") ; printf ("Word is palindrome\n" );
scanf("%s",str) ; else
j=strlen(str)-l; printf ("Word is not palindrome\n" );
while (i<=j )
{
if(str[i]==str[j])
flag=l;
else
Write a program to convert a
lowercase string into uppercase.
#include<stdio.h>
main( )
{
char str[10];
int i=0;
printf ("Enter a string in lowercase ") ;
scanf ("%s", str) ;
while(str[i] !='\0')
str[i]=str[i]-32;
i++;
}
printf ("The uppercase string is %s\n",str);
Unit 6

Files in C
Introduction
• The input and output operations that we have performed so far were done
through screen and keyboard only. After termination of program, all the entered
data is lost because primary memory is volatile.
• If the data has to be used later, then it becomes necessary to keep it in permanent
storage device.
• C supports the concept of files through which data can be stored on the disk or
secondary storage device.
• The stored data can be read whenever required
• . A file is a collection of related data placed on the disk
• The file handling in C can be broadly categorized in two types-
• High level(standard files or stream oriented files)
• Low level(system oriented files)
• High level file handling is managed by library functions while low leyel file handling
is managed by system calls.
Text And Binary Modes
• There are two ways of storing data in files, binary format and text format.
• In text format, data is stored as lines of characters with each line terminated by a
newline character('\n').
• In binary format, data stored on the disk in the same way as it is represented in the
computer memory.
• Unix system does not make any distinction between text file and binary files.
• Text files are in human readable form and they can be created and read using any
text editor, whreas binary files are not in human readable form and they can be
created and read only by specific program written for them. The binary data stored
in the file can't be read using a text editor.
Modes of File Opening
1. w" ( write)
If the file doesn't exist then this mode creates a new file for writing, and if the file already exist then the
previous data is erased and the new data entered is written to the file.
2. "a"( append)
If the file doesn't exist then this mode creates a new file, and if the file already exists then the data
entered is appended at the end of existing data. In this mode, the data existing in the file is
erased as in "w" mode.
3. "r" ( read)
This mode is used for opening an existing file for reading purpose only. The file to be opened if it exist
and the previous data of file is not erased.
4. "w+" (-write+read )
This' mode is same as "w" mode but in this mode we can also read and modify the data. If the doesn't
exist then a new file is created and if the file exists then previous data is erased.
5. "r+" ( read+write )
This mode is same as "r" mode but in this mode we can also write and modify existing data. The to be
opened must exist and the previous data of file is not erased. Since we can add new data & modify
existing data so this mode is also called update mode.
6. “a+" ( append+read )
This mode is same as the "a" mode but in this mode we can also read the data stored in the file. If The
file doesn't exist, a new file is created and if the file already exists then new data is appended at of
existing data. We cannot modify existing data in this mode.
Files in C
• The statement:
FILE *fptr1, *fptr2 ;
declares that fptr1 and fptr2 are pointer variables of type FILE. They will
be assigned the address of a file descriptor, that is, an area of memory that
will be associated with an input or output stream.

• Whenever you are to read from or write to the file, you must first open the
file and assign the address of its file descriptor (or structure) to the file
pointer variable.
Opening Files
• The statement:
fptr1 = fopen ( "mydata", "r" ) ;
would open the file mydata for input (reading).

• The statement:
fptr2 = fopen ("results", "w" ) ;
would open the file results for output (writing).

• Once the files are open, they stay open until you close them or end the
program (which will close all files.)
Testing for Successful Open

• If the file was not able to be opened, then the value returned by the fopen
routine is NULL.
• For example, let's assume that the file mydata does not exist. Then:
FILE *fptr1 ;
fptr1 = fopen ( "mydata", "r") ;
if (fptr1 == NULL)
{
printf ("File 'mydata' did not open.\n") ;
}
Reading From Files

• In the following segment of C language code:

int a, b ;
FILE *fptr1, *fptr2 ;
fptr1 = fopen ( "mydata", "r" ) ;
fscanf ( fptr1, "%d%d", &a, &b) ;

the fscanf function would read values from the file "pointed" to by fptr1
and assign those values to a and b.
End of File

• The end-of-file indicator informs the program when there are no more data
(no more bytes) to be processed.

• There are a number of ways to test for the end-of-file condition. One is to use
the feof function which returns a true or false condition:
fscanf (fptr1, "%d", &var) ;
if ( feof (fptr1) )
{
printf ("End-of-file encountered.\n”);
}
End of File

• There are a number of ways to test for the end-of-file condition. Another
way is to use the value returned by the fscanf function:
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == EOF )
{
printf ("End-of-file encountered.\n”) ;
}
Closing Files

• The file that was opened using fopen( ) function must be closed when no
more operations are to be performed on it. After closing the file, connection
between file and program is broken.
• Upon closing the file, all the buffers associated with it are flushed i.e. all
the data that is in the buffer is written to the file.
• Syntax: int fclose(FILE *fptr);

Example: fclose ( fptr1 ) ;


fclose ( fptr2 ) ;

will close the files and release the file descriptor space and I/O buffer
memory.
Character I/O functions: 1) fputc ( )
Syntax: int fputc( int c, FILE *fptr);
This function writes a character to the specified file at the current file position and then
increments position pointer. 'On success it returns an integer. representing the character
written, and on error returns EOF.
#include<stdio.h>
main()
{
FILE *fptr;
int ch;.
If (fptr=fopen("myfile.txt",Ow"))==NULL)
printf ("File does not exist\n");
exit() ;
else
printf ("Enter text : \n" ) ;
while ( (ch=getchar ( ) ) ! =EOF)
fputc (ch,fptr);
fclose (fptr) ;
• getc() and putc( )
• The operations of getc() and putc() are exactly similar to that of fgetc() and
fputc(), the only difference is that the former two are defined as macros
while the latter two are functions
2. fgetc()
Declaration: int fgetc( FILE *fptr );
• This function reads a single character from a given file and increments the file
pointer position. Upon success it returns the character after converting it to an
int without sign extension. On end of file error it returns EOF.

#include<stdio.h>
main ()
{
FILE *p;
char ch;
if((p=fopen("myfile.txt", "r"))==NULL)
printf ("This file doesn't exist\n");
else
while(ch=fgetc(p)!=EOF)
printf ("%c", ch);
}
fclose (p) ;
}
Program to Create/open file in C
#include <stdio.h>
main( )
{
FILE fsource;
char ch ;
printf("\n Input the data to be copied in the file :=” );
fsource = fopen("INPUT.TXT", "w");
while((c=getchar( )) != EOF) /* Get a character from keyboard */
putc(c,fl); /* Write a character to INPUT.TXT */
fclose(fsource );
printf("\nData Output Form the file := ");
fsource = fopen("INPUT.TXT","r"); /*.Reopen the file INPUT.TXT */
while((c=getc(fl)) != EOF) /* Read a character from INPUT.TXT
{
printf("%c",c); /* Display a character on screen */
fclose(f source) /* Close the file INPUT */
getch();
}
}
Program 2 :- File Copy program in C
# include "stdio.h"
main( )
{
FILE *fsource , *fdestn ;
char ch ;
fsource = fopen ("Prog.c", "r")
if (fsource == NULL)
{ puts ( "Cannot open source file"); exit(0); }
fdestn = fopen("New.c", "w");
if (fdestn == NULL)
{ puts ( "Cannot open target file" );
fclose(fs) exit( 0);
}
while (1)
{ ch = getc( fsource)
if (ch == EOF) break
else putc (ch, ft) ; }
fclose ( fsource);
fclose (fdestn);
}
The Preprocessor
• The C preprocessor permits you to define simple macros that are evaluated
and expanded prior to compilation.
• Commands begin with a ‘#’. Abbreviated list:
– #define: defines a macro
– #undef : removes a macro definition
– #include: insert text from file
– #if : conditional based on value of expression
– #ifdef : conditional based on whether macro defined
– #ifndef : conditional based on whether macro is not defined
– #else: alternative
– #elif: conditional alternative
– defined : preprocessor function: 1 if name defined, else 0
Command Line Argument in C
• Command line argument is a parameter supplied to the program when it is
invoked.
• Command line argument is an important concept in C programming. It is
mostly used when you need to control your program from outside.
Command line arguments are passed to the main() method.
• Syntax:int main(int argc, char *argv[])
• Here argc (ARGument Count) counts the number of arguments on the
command line and argv[ ] (ARGument Vector) is a pointer array which
holds pointers of type char which points to the arguments passed to the
program.
Example of Command Line Arguments

#include <stdio.h>
#include <conio.h>
main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
Program to copy a file to another using Command Line Arguments
• #include<stdio.h> • if( (dest=fopen(argv[2], "w")
• main (int argc, char *argv [ ]) )==NULL)
• FILE * source, *dest, * fopen ( ) ; • {
• int c; • printf (" Can't open destination file\n");
• if(argc!=3) • exit ( 1) ;
• { • }
• printf ("Wrong number of • while((ch=fgetc(source» !=EOF)
arguments\n"); • fputc(dest,c) ;
• exit (1) ; • fclose(source) ;
• } • fclose(dest) ;
• if( (source=fopen(argv[l],
"r"»==NULL)
• {
• printf(U Can't open source file\n");
• exit(1) ;
• }

You might also like