1. What is an array? How to declare and initialize arrays? Explain with examples
Ans: Array:-
An array is defined as an ordered set of similar data items. All the data items of an
array are stored in consecutive memory locations in RAM. The elements of an array
are of same data type and each item can be accessed using the same name.
Declaration of an array:- We know that all the variables are declared before they are
used in the program. Similarly, an array must be declared before it is used. During
declaration, the size of the array has to be specified. The size used during declaration
of the array informs the compiler to allocate and reserve the specified memory
locations.
float x[10];
Initialization of Arrays:-
We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.
Initializing all specified memory locations:- Arrays can be initialized at the time of
declaration when their initial values are known in advance. Array elements can be
initialized with data items of type int, char etc.
1
int a[3]={9,2,4,5,6};//error: no. of initial vales are more than the size of array.
Declaration:-
Syntax: data_type array_name[row_size][column_size];
Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the
second row to one. The initialization is done row by row.
When the array is completely initialized with all values, explicitly we need not
2
If the values are missing in an initializer, they are automatically set to zero.
for a 2D array?
In Row-Major Implementation of the arrays, the arrays are stored in the memory in
terms of the row design, i.e. first the first row of the array is stored in the memory then
second and so on. Suppose we have an array named arr having 3 rows and 3 columns
then it can be stored in the memory in the following manner :
int arr[3][3];
3
1 2 3 4 5 6 7 8 9
In Column-Major Implementationof the arrays, the arrays are stored in the memory in
the term of the column design, i.e. the first column of the array is stored in the memory
then the second and so on. By taking above eg. we can show it as follows :
arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
and it will be represented in the memory with column major implementation as follows :
1 4 7 2 5 8 3 6 9
Declaration:-
Syntax: data_type array_name[row_size][column_size];
Ex: int arr[3][3] ;
Where first index value shows the number of the rows and second index value shows the
no. of the columns in the array.
4
Initialization :-
To initialize values for variable length arrays we can use scanf statement and loop
constructs.
Ex:-
for (i=0 ; i<3; i++)
for(j=0;j<3;j++)
scanf(%d,&arr[i][j]);
where first index value shows the number of the rows and second index value shows the
number of the columns in the array. To access the various elements in 2-D array we can
use:
printf("%d", a[2][3]);
/* output will be 6, as a[2][3] means third element of the second row of the array */
In 3-D we can declare the array in the following manner :
int arr[3][3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
5
/* here we have divided array into grid for sake of convenience as in above
declaration we have created 3 different grids, each have rows and columns */
If we want to access the element the in 3-D array we can do it as follows :
printf("%d",a[2][2][2]);
/* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no.
i.e. 3 and the second value in [] means third row in the corresponding grid and last []
means third column */
Ex:-
int arr[3][5][12];
float table[5][4][5][3];
arr is 3D array declared to contain 180 (3*5*12) int type elements. Similarly table is a 4D
array containing 300 elements of float type.
MATRICES*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n,p,q;
printf("\n Enter the size of Matrix A:");
scanf("%d%d", &m,&n);
printf("\n Enter the size of Matrix B:");
scanf("%d%d", &p,&q);
6
if(m!=p || n!=q)
{ printf("Matrix addition not possible.");
exit(0); }
printf(" Enter the Matrix A values:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf(" Enter the Matrix B values:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\n The Matrix A is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d",a[i][j]);
printf("\n");
}
printf("\n The Matrix B is\n");
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
printf(" %d",b[i][j]);
7
printf("\n");
}
printf("\n The Output Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d",c[i][j]);
printf("\n");
} }
OUTPUT:
8
3
1
The Matrix A is
123
456
The Matrix B is
654
321
The Output Matrix C is
777
777
9
if(n!=p)
{
printf("Matrix Multiplication not possible.");
exit(0);
}
printf(" Enter the Matrix A values:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf(" Enter the Matrix B values:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{ c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j]; }
printf("\n The Matrix A is\n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
printf(" %d",a[i][j]);
printf("\n"); }
printf("\n The Matrix B is\n");
10
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
printf(" %d",b[i][j]);
printf("\n"); }
printf("\n The Output Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf(" %d",c[i][j]);
printf("\n");
}
}
OUTPUT:
Enter the size of Matrix A:2
3
2
2
2
2
2
11
2
The Matrix A is
222
222
The Matrix B is
33
33
33
15 15
15 5
12
Strings
7. Define C string? How to declare and initialize C strings with an
Declaring Strings:-
C does not support string as a data type. It allows us to represent strings as character
arrays. In C, a string variable is any valid C variable name and is always declared as an
array of characters.
The string city size is 8 but it contains 7 characters and one character space is for NULL
terminator.
13
A string is stored in array, the name of the string is a pointer to the beginning of the
string.
The character requires only one memory location.
If we use one-character string it requires two locations. The difference is shown below,
The difference between array and string is shown below,
Because strings are variable-length structure, we must provide enough room for
maximum-length string to store and one byte for delimiter.
C language provides several string handling functions for input and output.
14
String Input/Output Functions:-
C provides two basic methods to read and write strings. Using formatted input/output
functions and using a special set of functions.
(1) getchar():- It is used to read a single character from keyboard. Using this function
repeatedly we may read entire line of text
Ex:- char
ch=z;
ch=getch
ar();
(2) gets():- It is more convenient method of reading a string of text including blank
spaces.
Ex:- char
line[100];
gets(line);
15
Ex:- char name[10];
printf(%s,name);
Ex:- char name[10];
printf(%0.4,name);
Printf(%10.4s,name);
printf(%-10.4s,name);
Ex:- putchar(ch);
9. Explain about the following string handling functions with example programs.
(i) strlen (ii) strcpy (iii) strcmp (iv) strcat
Ans:
C supports a number of string handling functions. All of these built-in functions are
aimed at performing various operations on strings and they are defined in the header
file string.h.
16
(i). strlen( )
This function is used to find the length of the string excluding the NULL character. In
other words, this function is used to count the number of characters in a string. Its
syntax is as follows:
Int strlen(string);
gets(string1);
length=strlen(string1);
printf(\n The length of string=%d,length);
}
(ii). strcpy( )
This function is used to copy one string to the other. Its syntax is as follows:
strcpy(string1,string2);
17
This function copies the content of string2 to string1.
E.g., string1 contains master and string2 contains madam, then string1 holds
madam after execution of the strcpy (string1,string2) function.
(iii). strcmp ( )
This function compares two strings character by character (ASCII comparison) and
returns one of three values {-1,0,1}. The numeric difference is 0 if strings are equal .If
it is negative string1 is alphabetically above string2 .If it is positive string2 is
alphabetically above string1.
18
Int strcmp(string1,string2);
19
This function is used to concatenate two strings. i.e., it appends one string at the end of
the specified string. Its syntax as follows:
strcat(string1,string2);
20
Pointers
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address. The general form of a pointer variable declaration
is
Here, type is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk
used for multiplication. However, in this statement the asterisk is being used to designate
a variable as a pointer. Take a look at some of the valid pointer declarations
Examples:
21
This is done by using unary operator * that returns the value of the variable located at the
address specified by its operand. The following example makes use of these operations
#include <stdio.h>
int main ( )
{
return 0;
}
When the above code is compiled and executed, it produces the following result
Output:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable declaration.
A pointer that is assigned NULL is called a nullpointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program
#include <stdio.h>
22
int main ( )
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not intended to
point to an accessible memory location. But by convention, if a pointer contains the null
(zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming.
The following important pointer concepts should be clear to any C programmer
1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers
You can define arrays to hold a number of pointers.
3 Pointer to pointer
C allows you to have pointer on a pointer and so on.
23
dynamically allocated memory as well.
#include<stdio.h>
#include<conio.h>
void main() {
int int_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;
/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;
/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n", int_ptr);
printf("After increment address in char_ptr = %u\n", char_ptr);
24
printf("After increment address in float_ptr = %u\n\n", float_ptr);
/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;
getch();
return 0;
}
Output
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292
Generic Pointers
This is very useful when you want a pointer to point to data of different types at different
times.
25
Here is some code using a void pointer:
generic_pointer.c
int
main()
{
int i;
char c;
void *the_data;
i = 6;
c = 'a';
the_data = &i;
printf("the_data points to the integer value %d\n", *(int*) the_data);
the_data = &c;
printf("the_data now points to the character %c\n", *(char*) the_data);
return 0; }
Following is a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function
#include <stdio.h>
#include <time.h>
void getSeconds(unsigned long *par);
int main ( )
{
26
return 0;
}
/* function declaration */
double getAverage(int *arr, int size);
int main ( )
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
int i, sum = 0;
double avg;
27
for (i = 0; i < size; ++i) {
sum += arr[i];
}
When the above code is compiled together and executed, it produces the following result
Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable takes different addresses as value whereas, in
case of array it is fixed.
This can be demonstrated by an example:
#include <stdio.h>
int main()
{ char charArr[4];
int i;
for(i = 0; i < 4; ++i)
{ printf("Address of charArr[%d] = %u\n", i, &charArr[i]); }
28
return 0; }
When you run the program, the output will be:
Address of charArr[0] = 28ff44
Address of charArr[1] = 28ff45
Address of charArr[2] = 28ff46
Address of charArr[3] = 28ff47
Note: You may get different address of an array.
Notice, that there is an equal difference (difference of 1 byte) between any two
consecutive elements of array charArr.
But, since pointers just point at the location of another variable, it can store any address.
In C programming, name of the array always points to address of the first element of an
array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
..
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
29
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
Pointer Array
1. A pointer is a place in 1. An array is a single, pre
memory that keeps allocated chunk of
address of another place contiguous elements (all
inside of the same type), fixed in
size and location.
2. Pointer cant be 2. Array can be initialized
initialized at definition. at definition. Example
int num[] = { 2, 4, 5}
3. Pointer is dynamic in 3. They are static in
nature. The memory nature. Once memory is
allocation can be resized allocated , it cannot be
or freed later. resized or freed
dynamically.
4. The assembly code of 4. The assembly code of
30
Pointer is different than Array is different than
Array Pointer.
31
int main()
{
int ageArray[ ] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.
return 0;
}
Output
4
int main()
{
float avg, age[ ] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}
32
}
avg = (sum / 6);
return avg;
}
Output
Average age=27.08
Structures
A structure allows you to wrap one or more variables that may be in different
data types into one. It can contain any valid data type like int ,char, float, array,
pointer or even structures. Each variable in the structure is called a structure
member.
Defining a structure
To define a structure, you use the struct keyword.
33
Or, you can declare the structure variable after you define the structure:
struct struct_name instance_1,instance_2 instance_n;
typedef struct{
char first[32]; //first field an array of chars
char last[32]; //second field an array of chars }person;
person student;
person teacher;
structure_name.structure_member
The following example demonstrates how to access the first name of
structure person:
person student;
student.first = "Richard";
We can also use the dot operator to access a nested structure and its members:
typedef struct{
person teacher[0];
person students[50];
}course;
34
course COMP2401;
COMP2401.students[0].first = "Richard";
Advantages of structures
Having a label that refers to the entire structure is convenient for two reasons.
First, it allows assignment statements between structure variables. This
allows you to copy data from one structure to another:
struct_intance1 = struct_intance2
Second, is passing a structure as a parameter to a function:
displayStudent(person info){
printf( %s %s: %d, info.first info.last, info.age);
}
Arrays and Structures
Just like you can have an array of any data type, you can have an array of structs.
typedef struct{
strcpy(students[0].last, Ison);
students[0].age = 19;
35
Pointers and Structures
The address of a structure variable can be stored in a pointer variable, just
like the address of any other type of variable.
struct fraction {
int x, y; };
struct fraction f[3], *g;
f[0].x=3;
f[0].y = 5;
g = &(f[0]);
There are two syntaxes to access the bytes of the structure using the
pointer variable.
(*g).x = 5;
Union
Definition
A union is a type of structure that can be used where the amount of memory used is a
key factor. Similarly to the structure the union can contain different types of data types.
Each time a new variable is initialized from the union it overwrites the previous and uses
that memory location. This is most useful when the type of data being passed through
functions is unknown, using a union which contains all possible data types can remedy
this problem.
Defining a Union
union person {
char name;
int age;
double height; };
36
Declaring a Union
Since the union is still a type of structure the method for declaring it is as follows:
union person {
char name;
int age;
double height;
} newPerson;
Or Person newPerson;
Initializing a Union
The process of initializing variables in a union is the same as a union but the results
are what make unions unique. The dot operator is still used in order to reach the data
types inside of the union.
Person newPerson;
newPerson.age = 20;
newPerson.height = 6.2;
Once the height variable is initialized the variable age is overwritten and no longer exists.
ENUM
Defining an Enumeration
An enumeration provides the data type with a set of values. An enumeration constant is a
type of an integer. A variable type takes and stores the values of the enumeration set
defined by that type. Enumerations can be used with indexing expressions also as
operands with arithmetic and relational operators. Enumerations can be also be used as an
alternate way to use #define.
An enumeration is a user-defined data type that consists of integral constants. To define
an enumeration, keyword enum is used.
enum flag { const1, const2, ..., constN };
Here, name of the enumeration is flag.
And, const1, const2,...., constN are values of type flag.
37
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum
elements during declaration (if necessary).
38
}
Output
Day 4
Advantages of Enumerations
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following
are the functions,
Function description
39
ftell() gives current position in the file
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
40
After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.
Closing a File
The fclose() function is used to close an already opened file.
General 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.
Predefined Streams :
41
A stream is linked to a file using an open operation. A stream is disassociated from
a file using a close operation. The current location, also referred to as the current
position, is the location in a file where the next file access will occur. There are two
types of streams: text (used with ASCII characters some character translation takes
place, may not be one-to-one correspondence between stream and what's in the file)
and binary (used with any type of data, no character translation, one-to-one between
stream and file).
To open a file and associate it with a stream, use fopen(). Its prototype is shown
here: FILE *fopen(char *fname,char *mode);
The fopen() function, like all the file-system functions, uses the header stdio.h . The
name of the file to open is pointed to by fname (must be a valid name). The string
pointed at for mode determines how the file may be accesed as shown:
Mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Open a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for
read/write
r+b Open a binary file for read/write
w+b Create a binary file for
read/write
a+b Append a binary file for
read/write
If the open operation is successful, fopen() returns a valid file pointer. The
type FILE is defined in stdio.h. It is a structure that holds various kinds of information
about the file, such as size.The file pointer will be used with all other functions that
operate on the file and it must never be altered or the object it points to.
42
If fopen() fails it returns a NULL pointer so this must always be checked for when
opening a file. For example:
FILE *fp;
exit(1);
The fclose() function closes the file associated with fp, which must be a valid file
pointer previously obtained using fopen(), and disassociates the streamfrom the file.
The fclose() function returns 0 if successful and EOF (end of file) if an error occurs.
Once a file has been opened, depending upon its mode, you may read and/or write
bytes to or from it using these two functions.
The getc() function reads the next byte from the file and returns its as an integer and
if error occurs returns EOF. The getc() function also returns EOFwhen the end of file is
reached. Your routine can assign fget()'s return value to a char you don't have to
assign it to an integer.
The fput() function writes the bytes contained in ch to the file associated with fp as an
unsigned char. Although ch is defined as an int, you may call it using simply a char.
The fput() function returns the character written if successful or EOF if an error occurs.
TYPES OF FILES
43
There are 2 kinds of files in which data can be stored in 2 ways either in characters coded in
their ASCII character set or in binary format. They are
Text Files.
Binary Files
TEXT FILES
A Text file contains only the text information like alphabets ,digits and special symbols. The ASCII code of
these characters are stored in these files.It uses only 7 bits allowing 8 bit to be zero.
1.w(write):
This mode opens new file on the disk for writing.If the file exist,disk for writing.If the file exist, then it will
be over written without then it will be over written without any confirmation.
SYNTAX:
1 fp=fopen("data.txt","w");
2 "data.txt" is filename
3 "w" is writemode.
2. r (read)
This mode opens an preexisting file for reading.If the file doesnt Exist then the compiler
returns a NULL to the file pointer
SYNTAX:
fp=fopen("data.txt","r");
3. w+(read and write)
This mode searches for a file if it is found contents are destroyed If the file doesnt found
a new file is created.
SYNTAX:
fp=fopen("data.txt","w+");
4.a(append)
This mode opens a preexisting file for appending the data.
SYNTAX:
fp=fopen("data.txt","a");
5.a+(append+read)
44
the end of the file.
SYNTAX:
fp=fopen("data.txt","a+");
6.r+ (read +write)
This mode is used for both Reading and writing
BINARY FILES
A binary file is a file that uses all 8 bits of a byte for storing the information .It is the form
which can be interpreted and understood by the computer.
The only difference between the text file and binary file is the data contain in text file can
be recognized by the word processor while binary file data cant be recognized by a word
processor.
1.wb(write)
this opens a binary file in write mode.
SYNTAX:
fp=fopen(data.dat,wb);
2.rb(read)
this opens a binary file in read mode
SYNTAX:
fp=fopen(data.dat,rb);
3.ab(append)
this opens a binary file in a Append mode i.e. data can be added at the end of file.
SYNTAX:
fp=fopen(data.dat,ab);
4.r+b(read+write)
this mode opens preexisting File in read and write mode.
SYNTAX:
fp=fopen(data.dat,r+b);
5.w+b(write+read)
45
this mode creates a new file for reading and writing in Binary mode.
SYNTAX:
fp=fopen(data.dat,w+b);
6.a+b(append+write)
this mode opens a file in append mode i.e. data can be written at the end of file.
SYNTAX:
fp=fopen(data.dat,a+b);
46
2 End of file
Ex:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is
skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current
position.
2. ftell()
This function returns the value of the current pointer position in the file.The value is
count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
47
Where fptr is a file pointer.
#include<stdio.h>
#include<conio.h>
void main()
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
else
{
printf("Enter value of n to read last n characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
printf("%c\t",ch);
48
}
fclose(fp);
getch();
49
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
fclose(fp);
return(0);
}
Let us assume we have a text file file.txt that have the following content
This is tutorialspoint.com
Now let us compile and run the above program to produce the following result
This is tutorialspoint.com
This is tutorialspoint.com
feof
int feof ( FILE * stream );
50
This indicator is generally set by a previous operation on the stream that attempted to
read at or past the end-of-file.
Notice that stream's internal position indicator may point to the end-of-file for the next
operation, but still, the end-of-file indicator may not be set until an operation attempts to
read at that point.
This indicator is cleared by a call to clearerr, rewind, fseek, fsetpos or freopen. Although
if the position indicator is not repositioned by such a call, the next i/o operation is likely
to set the indicator again.
Parameters
Stream- Pointer to a FILE object that identifies the stream.
Return Value
A non-zero value is returned in the case that the end-of-file indicator associated with the
stream is set. Otherwise, zero is returned.
Example
/* feof example: byte counter */
#include <stdio.h>
int main ()
{
FILE * pFile;
int n = 0;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL) perror ("Error opening file");
else
{
while (fgetc(pFile) != EOF) {
51
++n;
}
if (feof(pFile)) {
puts ("End-of-File reached.");
printf ("Total number of bytes read: %d\n", n);
}
else puts ("End-of-File was not reached.");
fclose (pFile);
}
return 0;
}
This code opens the file called myfile.txt, and counts the number of characters that it
contains by reading all of them one by one. The program checks whether the end-of-file
was reached, and if so, prints the total number of bytes read.
52
fclose(fp);
}
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are refering to the same file
but in different modes. fprintf() function directly writes into the file, while fscanf() reads
from the file, which can then be printed on console usinf standard printf() function.
Command Line Argument
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 main() method.
53
Syntax :
int main( int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer
array which holds pointers of type char which points to the arguments passed to the
program.
54
Mucho más que documentos.
Descubra todo lo que Scribd tiene para ofrecer, incluyendo libros y audiolibros de importantes editoriales.
Cancele en cualquier momento.