Unite28093v Character Arrays Strings File
Unite28093v Character Arrays Strings File
Example 2:
char name[10]= “WELL DONE”;
which declares the name as a character array variable that can hold a maximum of 10
characters.
When the compiler sees a character string, then it terminate it with an additional null character.
So, the element name[9] holds the null character ‘\0’.
When declaring character arrays, we must allow one extra element space for the null
character(‘\0’).
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[50]={“SACHIN RAMESH TENDULKAR”};
char fname[10],mname[20],lname[10];
sscanf(name,”%s %s %s”,fname,mname,lname);
printf(“First Name = %s“,fname);
printf(“Middle Name = %s“,mname);
printf(“Last Name = %s“,lname);
getch();
}
sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the formatted
text to a character array.
Syntax:
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[50];
char fname[10]= {“SACHIN”};
char mname[20]={“RAMESH”};
char lname[10]={“TENDULKAR”};
sprintf(name,”%s %s %s”,fname,mname,lname);
printf(“Full Name = %s”,name);
getch();
}
When the compiler assigns a character string to a character array, it automatically supplies a null
character ‘\0’ at the end of the string.
Therefore, the size should be equal to the maximum number of characters in the string plus one.
Initialization of String Variable
Example:
char city[9]=“NEW YORK”;
char city[9]={‘N’,’E’,’W’,’ ’,’Y’,’O’,’R’,’K’,’\0’};
When we initialize a character array by listing its elements, we must supply explicitly the null
terminator.
1) strcat( ) function
It joins two string together.
Syntax:
strcat(string1, string2);
Where, string1 & string2 are character arrays.
Example:
char str1[10] = “Good”;
char str2 [10]= “Morning”;
strcat(str1, str2);
printf(“str1 = %s”,str1);
Output
Str1 = GoodMorning
strcat function may also append a string constant to a string variable.
strcat(str1, “Morning”);
C also supports nesting of strcat functions.
strcat(strcat(str1,str2), str3);
which concatenates all the three string together and the final string is stored in str1.
2) strcmp( ) function
It compares two strings and return 0 if they are equal.
If they are not equal, then it has numeric difference between the first nonmatching characters in
the strings.
Syntax:
strcmp(string1, string2);
.
Example 1:
char str1[10]=“ram”;
char str2[10]=“ram”;
strcmp(str1, str2);
Example 2:
strcmp(“RAJA”, “ROJA”)
In example 1 both the strings are same so the function strcmp return 0.
In example 2 both strings are different so the function strcmp returns the numeric difference
between ASCII “A” and ASCII “O”. Which is -14.
If the return value is negative it means string1 is alphabetically above to string2.
3) strcpy( ) function
It is a one type of string-assignment operator.
Syntax:
strcpy(string1, string2);
Example:
strcpy(subject, “PC”);
Which assign the string “PC” to string variable subject.
Similarly, the statement strcpy(name1, name2); will assign the contents of the string variable
name2 to the string variable name1.
But, the size of array name1 should be large enough to store the content of name2.
strlen( ) function
It is used to count the length of string or number of characters in a string.
Syntax:
int n = strlen(string);
Where n is an integer variable, which stores the length of the string.
The counting end at the first null character.
strcmp( ) function
It compares two strings and return 0 if they are equal.
If they are not equal, then it has numeric difference between the first nonmatching characters in
the strings.
Syntax:
strcmp(string1, string2);
.
Example 1:
char str1[10]=“ram”;
char str2[10]=“ram”;
strcmp(str1, str2);
Example 2:
strcmp(“RAJA”, “ROJA”)
In example 1 both the strings are same so the function strcmp return 0.
In example 2 both strings are different so the function strcmp returns the numeric difference
between ASCII “A” and ASCII “O”. Which is -14.
If the return value is negative it means string1 is alphabetically above to string2.
char str[50],revstr[50];
int i,j=0,n;
printf("Enter the string to be reversed : ");
gets(str);
n=strlen(str);
for(i=n-1;i>=0;i--)
{
revstr[j]=str[i];
j++;
}
revstr[j]='\0';
if(strcmp(revstr,str)==0)
{
printf("\nThe string is a palindrome");
}
else
{
printf("\nThe string is not a palindrome");
}
getch();
}
10) Give the syntax of gets () and puts () function and Explain with Example.
Answer:
gets() function
gets() accepts any line of string including spaces from the keyboard.
gets() stops reading character from keyboard only when the enter key is pressed.
Syntax:
gets (variable_name);
puts () function
puts displays a single / paragraph of text to the standard output device.
Syntax:
puts (variable_name);
Example: #include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
gets(a);
puts(a);
getch();
}
Files
1) What is File Management?
Answer:
The printf() and scanf() function are used for to read and write the data.
With the use of these functions, the entire data is lost when either the program is terminated or the
computer is turned off.
With the help of Files, we can store data on disks and read when necessary.
A file is a place on the disk where a group of related data is stored.
Text Files are human readable and it is a stream of plain English characters.
Binary Files are not human readable. It is a stream of processed characters and ASCII symbols.
C supports basic file operations which includes,
(1) Naming a file
(2) Opening a file
(3) Reading data from a file
(4) Writing data to a file
(5) Closing a file
Answer:
Function Operation
Name
fopen() Creates s new file for use OR Opens an existing file for use
fclose() Closes a file which has been opened for use
fgetc() Reads a character from a file
fputc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
fgetw() Reads an integer from a file
fputw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the fie
Answer:
Mode Working
Answer:
fopen():
Creates s new file for use OR Opens an existing file for use
Syntax: FILE *fp;
fp=fopen(“Filename”,”mode”);
Here, FP is a pointer to the data type FILE.
Second statement open a file named filename and assign an identifier to the FILe type.
Mode specify the purpose of opening this file.
Example: FILE *fp;
fp=fopen(“pr1.c”,”r”);
fclose():
Closes a file which has been opened for use
A file must be closed as soon as all operation are over.
Syntax: fclose(File Pointer);
Example: FILE *fp;
fp=fopen(“pr1.c”,”r”);
- - - - -
fclose(fp);
fgetc():
Reads a character from a file.
This function handle one character at a time.
Prepared By: Computer Department, VPMP Page 9
Subject Name: Computer Programming Fundamentals Unit No: 05
Syntax: c= fgetc(fp);
Here c is a character type variable and fp is a file pointer.
This statement reads a character from a file that has been open in read mode.
putc():
Writes a character to a file
Syntax:fputc(c, fp);
Here c is a character type variable and fp is a file pointer.
This statement writes a character contained in the character variable c to the file ,which is pointed by
fp.
fgetw():
a. Reads an integer from a file
Syntax: integer variable=getw(fp);
fputw():
Writes an integer to a file
Syntax: putw(integer,fp);
feof():
It returns non zero value only if end of file has reached, otherwise return zero.
Syntax: feof(fp);
fprintf():
fprintf() write all the data written in list to the file.
Syntax: fprintf(fp, “control string”, list);
fscanf():
fscanf() reads data from file and store in variables declared in list.
Syntax: fscanf(fp, “control string”, list);
Where, fp is a file pointer associated with a file.
Answer:
A command line argument is a parameter which is passed to a program at the time when it is
executed from the command line.
Program execution always start with main() Function.
Main() can have arguments.
After successful compilation and linking, compiler generates exe file.
These arguments are passed with executable file.
2. printf()
It is used to display all types of data and messages.
It can display multiple data at a time by multiple format specifier in one printf().
Example: printf(“a=%d b=%d” ,a, b);
3. gets()
It is unformatted input function.
It is used to read a single string with white spaces.
Example: char str[10];
gets(str);
4. getchar(),getche(),getch()
It is unformatted input function.
puts(str);
6. putchar()
It is unformatted output function.
It is used to display single character at a time.
Example: putchar(ch);
To detect I/O errors in the file, we can use the feof and ferror function.
FEOF():
It display the message End of data, on reaching the end of file condition.
FERROR ():
It reports the status of the file indicated.
It takes FILE pointer as argument and error has been detected ,then return non zero, otherwise it return
zero.
Example:
if (ferror(fp)!=0)
printf(“An error has occured\n”);
If the reading is not successful, then an error has occurred.
A file pointer is a pointer to a structure, which contains information about the file, including its name,
current position of the file, whether the file is being read or written, and whether errors or end of the file
have occurred.
Example: FILE *fp;
Here, fp is the file pointer that points to a FILE structure.
10) Give the difference between text mode file and binary mode file.
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("a.txt","r");
c='A';
putc(c,fp);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("a.txt","r");
c = getc(fp);
printf(“ % c”, c);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("abc.txt","w");
printf("Enter string\n");
c= getchar();
while( c != EOF)
{
fputc(c,fp);
c=getchar();
}
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("abc.txt","w");
c=fgetc(fp);
while( c != EOF)
{ printf("%c",c);
c=fgetc(fp);
}
fclose(fp);
getch();
}
15) Write a C Program to copy a File.
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *r,*w;
clrscr();
r=fopen("pro.txt","r");
w=fopen("pronew.txt","w");
c=fgetc(r);
while( c != EOF)
{ fputc(c,w);
c=fgetc(r);
}
fclose(r);
fclose(w);
getch();
}
16) Write a program to Merge the content of one file with another file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
char ch;
clrscr();
f1=fopen("file1.txt","r");
f2=fopen("file2.txt","r");
f3=fopen("file3.txt","w");
while((ch=fgetc(f1))!=EOF)
{
fputc(ch,f3);
}
while((ch=fgetc(f2))!=EOF)
{
fputc(ch,f3);
}
printf("The File1 and File2 merged in File3\n");
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char name[10];
int id;
FILE *fp;
fp=fopen("a.txt","r");
clrscr();
fscanf(fp,"%s %d",name,&id);
printf("name is:%s\n",name);
printf("id is:%d",id);
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char name[10]="Hello";
int id=1;
clrscr();
FILE *fp;
fp=fopen("a.txt","w");
fprintf(fp,"%s %d",name,id);
fclose(fp);
getch();
}