Advanced C 2 Marks

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 25

UNIT 1 (CONSTRUCTS OF C)

1. What is programming paradigms?


 A programming paradigm is a fundamental style of programming that defines how the
structure and basic elements of a computer program will be built.

2. What are the classifications of programming paradigms?


 Monolithic programming
 Procedural programming
 Structured programming
 Object oriented programming
 Logic oriented programming
 Rule oriented programming
 Constraint oriented programming

3. List out some characteristics of C.


 High level programming language
 Structured programming
 Portable language
 Extensible language

4. Give the structure of C program.


 Document Section
 Link Section
 Definition Section
 Global Declarations
 main ()
 {
 Declarations;
 Valid program statements;
 }
 Sub program section
 Function 1
 Function 2
1
o -
 Function N

5. List some uses of C language.


 Used for system programming
 Compilers, libraries, interpreters are often implemented in C
 Used to implement end-user applications

6. What are the different data types available in ‘C’?


 There are four basic data types available in ‘C’.
 int
 float
 char
 double

7. What are Keywords?


 Keywords are certain reserved words that have standard and pre-defined meaning in
‘C’. These keywords can be used only for their intended purpose.

8. What is an Operator and Operand?


 An operator is a symbol that specifies an operation to be performed on operands.
Example:
 *, +, -, / are called arithmetic operators.

 The data items that operators act upon are called operands.
Example:
 a+b; In this statement a and b are called operands.

9. What is Ternary operators or Conditional operators?


 Ternary operators is a conditional operator with symbols ? and :

 Syntax: variable = exp1 ? exp2 : exp3


 If the exp1 is true variable takes value of exp2. If the exp2 is false, variable takes the
value of exp3.

Example :
int result, a=35,b=40;
result = a<b? 10 : 20;
In the above example, if the expression a>b is evaluated to true then 10 is assigned to
result otherwise 20 is assigned to result.

10. What are the Bitwise operators available in ‘C’?


2
& - Bitwise AND
| - Bitwise OR
~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR are called bit field operators

11. What are the logical operators available in ‘C’?


The logical operators available in ‘C’ are

&& - Logical AND


|| - Logical OR
! - Logical NOT

12. What is the difference between Logical AND and Bitwise AND?
Logical AND (&&): Only used in conjunction with two expressions, to test more than one
condition. If both the conditions are true the returns 1. If false then return 0.

AND (&): Only used in Bitwise manipulation. It is a unary operator.

13. What is the difference between ‘=’ and ‘==’ operator?


Where = is an assignment operator and == is a relational operator.
Example:
while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only
when i=5.

14. What is type casting?


Type casting is the process of converting the value of an expression to a particular data type.
Example:
int x,y;
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into
float.

15. What is the difference between ‘a’ and “a”?


‘a’ is a character constant and “a” is a string.

16. What is the difference between if and while statement?


If while
(i) It is a conditional statement (i) It is a loop control statement
(ii) If the condition is true, it executes (ii) Executes the statements within the while
some statements. block if the condition is true.
3
(iii) If the condition is false then it(iii) If the condition is false the control is
stops the execution the statements. transferred to the next statement of the loop.

17. What is the difference between while loop and do…while loop? (JAN 2011/2013)
In the while loop the condition is first executed. If the condition is true then it executes the
body of the loop. When the condition is false it comes of the loop. In the do…while loop
first the statement is executed and then the condition is checked. The do…while loop will
execute at least one time even though the condition is false at the very first time.

18. What is a Modulo Operator?


‘%’ is modulo operator. It gives the remainder of an integer division
Example:
a=17, b=6. Then c=%b gives 5.

19. How many bytes are occupied by the int, char, float, long int and double?
int - 2 Bytes, char - 1 Byte, float - 4 Bytes, long int - 4 Bytes, double - 8 Bytes

20. What are the types of I/O statements available in ‘C’?


There are two types of I/O statements available in ‘C’.

Formatted I/O Statements


Unformatted I/O Statements

21. What is the difference between ++a and a++?


++a means do the increment before the operation (pre increment) a++ means do the increment
after the operation (post increment)
Example:
a=5;
x=a++; /* assign x=5*/
y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7*/

22. What is a String?


String is an array of characters and digits enclosed within double quote.

23. What is a global variable?


The global variable is a variable that is declared outside of all the functions. The global
variable is stored in memory, the default value is zero. Scope of this variable is available in all
the functions. Life as long as the program’s execution doesn’t come to an end.

4
24. What are the Escape Sequences present in ‘C’? (JAN 2013)
\n - New Line
\b - Backspace
\t - Form feed
\’ - Single quote
\\ - Backspace
\t - Tab
\r - Carriage return
\a - Alert
\” - Double quotes

25. Construct an infinite loop using while?


while (1)
{

}
Here 1 is a non zero, value so the condition is always true. So it is an infinite loop.

26. Write the limitations of getchar( ) and scanf( ) functions for reading strings
(JAN 2009)
getchar( )
read a single character from stdin, then getchar() is the appropriate.

scanf( )
scanf( ) allows to read more than just a single character at a time.

27. What is the difference between scanf() and gets() function? (MAY 2005)
In scanf() when there is a blank was typed, the scanf() assumes that it is an end.

gets() assumes the enter key as end. That is gets() gets a new line (\n) terminated string of
characters from the keyboard and replaces the ‘\n’ with ‘\0’.

28. What is meant by Control String in Input/Output Statements?


Control Statements contains the format code characters, specifies the type of data that the user
accessed within the Input/Output statements.

29. What is a preprocessor directive?


The preprocessor, as the name implies, is a program that processes the source code before it
passes through the compiler.

30. List some commonly used preprocessor directives.


5
#define
#include
#undef
#ifdef
#if
#else
#elif
#endif
#error
#pragma

31. What are the classifications of preprocessor directives?


Macro substitution directives

File inclusion directives


Compiler control directives (or) conditional inclusion
33. List out the rules for defining preprocessor.
Every preprocessor must start with # symbol
Preprocessor is always placed before main() function
Preprocessor cannot have termination with semicolon
There is no assignment operator in #define statement
The conditional macro must be terminated

34. Name some predefined macros.


_DATE_ -current date
_TIME_ - current time
_FILE_ - file name
_LINE_ - Line number

35. What are macros? What are its advantages and disadvantages?
Macros are abbreviations for lengthy and frequently used statements. When a macro is called
the entire code is substituted by a single line though the macro definition is of several lines.

The advantage of macro is that it reduces the time taken for control transfer as in case of
function.

36. What are the steps to be followed while executing a C program?


Creating the program
Compiling program
Linking the program with system library
Executing the program
6
37. What is the difference between static and auto storage classes?
Static Auto
Storage Memory Memory
Initial value Zero Garbage value
Local to the block in which Local to the block in which
Scope
the variables is defined the variable is defined.
Value of the variable Persists The block in which the
Life between different function variable is defined.
calls.

38. What do you mean by variables in “C”?

A variable is a data name used for storing a data value.


Can be assigned different values at different times during program execution.
Can be chosen by programmer in a meaningful way so as to reflect its function in the
program.
Some examples are: Sum percent_1 class_total

39. Write short notes about main ( ) function in “C” program. (MAY 2009)

Every C program must have main ( ) function


All functions in C, has to end with “( )” parenthesis.
It is a starting point of all “C” programs
The program execution starts from the opening brace “{“ and ends with closing brace “}”,
within which executable part of the program exists.

40. Differentiate break and continue statement. (APRIL 2008)

S.No. Break continue


1 Exits from current block / Loop takes next
loop iteration
2 Control passes to next Control passes to beginning of
Statement loop
3 Terminates the program Never terminates the program

41. List the types of operators. (JAN 2010/2011/2014)


S.No. Operators Types Symbolic Representation
1 Arithmetic operators +,-,*,/,%
2 Relational operators <,<=,>,>=,==,!=
3 Logical operators &&, ||, !
4 Increment and Decrement ++,--
operators
5 Assignment operators = , + = , -= , * = , / = , ^ = , ; = , & = 7
6 Bitwise operators & , | , ^ , >> , << , and ~
7 Comma operator ,
8 Conditional operator ?:
42. Distinguish between while..do and do..while statement in C. (JAN 2009/2011/2013)

While Do -While

Executes the statements within the while Executes the statements within the while
block if only the condition is true. block at least once.
The condition is checked at the starting The condition is checked at the end of the
of the loop loop
Top tested Bottom tested

43. Compare switch( ) and nested if statement.


Switch nested if
Test for equality ie., only constant It can equate relational (or)
values are applicable. logical expressions.
No two case statements in same switch. Same conditions may be repeated for a
Character constants are automatically number of times.
converted to integers. Character constants are automatically
In switch( ) case statement nested if can converted to integers.
be used. In nested if statement switch case can be
used.

44. Give the syntax for the ‘for’ loop statement.


for (Initialize counter; Test condition; Increment / Decrement)
{
statements;

45. What is the use of sizeof( ) operator?


The sizeof ( ) operator gives the bytes occupied by a variable.
No of bytes occupied varies from variable to variable depending upon its data types.
Example:
int x,y;
printf(“%d”,sizeof(x));
Output:
2

46. What is a loop control statement?


Many tasks done with the help of a computer are repetitive in nature. Such tasks can be done
with loop control statements.

8
47. What are global variable in ‘C’?
This section declares some variables that are used in more than one function. Such variable are
called as global variables.
It should be declared outside all functions.

48. Write a program to swap the values of two variables (without temporary variable).
#include <stdio.h>
#include <conio.h>
void main( )
{
int a =5; b = 10;
clrscr( );
prinf(“Before swapping a = %d b = %d “, a , b);
a = a + b; B = a – b;
a = a – b;
prinf(“After swapping a = %d b = %d”, a,b);
getch( );
}
Output:
Before swapping a = 5 b = 10
After swapping a = 10 b = 5

49. What is mean by explicit type conversion? Give example.


Converting one data type value into another data type explicitly is called explicit type
conversion. The general form of explicit type conversion

(Type-name)expression

Example:
int x;
x = int(7.5);

UNIT II ARRAYS AND FUNCTIONS

1. What is an array? Write the syntax to declare an array. Also give an example.
An array is a group of related data items that share a common name.
Syntax: data type arrayname[size];
9
Example: int a[10];

2. List the properties of array.


 Array elements are stored in continuous memory locations
 The type of an array is the data type of its elements
 The length of an array is the number of data elements in the array
 The location of an array is the location of its first element

3. What are the types of array?


One dimensional array- datatype arrayname[size];
Two dimensional array- datatype arrayname[rowsize][columnsize];
Multi dimensional array-datatype arrayname[s1][s2]…[sm];

4. What are the ways to initialize the array?


 Compile time initialization
 Run time initialization

5. What will happen when you access the array more than its dimension?
When you access the array more than its dimensions some garbage value is stored in the array.

6. What are the advantages of array?


It is capable of storing many elements at a time
It allows random access of elements

7. What are the disadvantages of array?


 The elements in the array must be same type
 Predetermining the size of array is must
 Memory wastage will be there, if the array of large size is defined
 To delete an element of an array we need to traverse throughout array

8. List some applications of array.


 Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
rectangular tables
 Many databases include one-dimensional arrays whose elements are records
 Arrays are also used to implement other data structures such as strings, stacks, queues,
heaps and hash tables
 Arrays can be used for sorting elements in ascending or descending order

9. How to initialize an array?


You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
10
The number of values between braces { } cannot be larger than the number of elements
that we declare for the array between square brackets [ ].

10. Why is it necessary to give the size of an array in an array declaration?


When an array is declared, the compiler allocates a base address and reserves enough space in
the memory for all the elements of the array. The size is required to allocate the required space.
Thus, the size must be mentioned.

11. How two dimensional arrays can be initialized? Give example / Define the syntax for
two dimensional array. (Jan 2011)/ May/June 2014
It is an array declared with two subscripts (row and column).
Syntax:
Data-type variablename[row_size][column_size];
Eg:
int ar[3][4]; ar holds 12 elements with 3 rows & 4 columns.

12. Declare a float array of size 5 and assign 5 values to it. (Nov 2015)
float height[5]={56.2,45.2,42.3,21.6,31.2};

13. Define Strings.


The group of characters, digit and symbols enclosed within quotes is called as String (or)
character Arrays. Strings are always terminated with “\0” (NULL) character. The compiler
automatically adds “\0” at the end of the strings.

Example: char name[]={“C”,”O”,”L”,”L”,”E”,”G”,”E”,”E”,”\0”};

14. How strings are represented in ‘C’ language? (JAN 2013) / What are strings? How are
they declared? (Jan 2010)
The group of characters, digit and symbols enclosed within quotes is called as String (or)
character Arrays. Strings are always terminated with ‘\0’ (NULL) character. The compiler
automatically adds ‘\0’ at the end of the strings.

15. List some of the string handling functions. (May/June 2014)


strcpy()
strcat()
strcmp()
strlen()
strrev()
strstr()

16. What is the use of ‘\0’ character?


When declaring character arrays (strings), ‘\0’ (NULL) character is automatically added at end.
The ‘\0’ character acts as an end of character array.

11
17. Why we don’t use ‘&’ symbol, while reading a string through scanf()?
String are represented using character array
Eg: char str[size]

In scanf, we need to pass the address to store the input.

In case of int, char, float, etc we need to provide address which is done by using '&' (address of
operator), whereas in case of character array: the name of the array itself represents the address
of the first element of the array hence no need of '&' just the name is required i.e str

18. Give the declaration for the string “welcome” in C.


Syntax:
char array_name[size]=”string”;
char mess[]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
or
char mess[]=”welcome”;

19. Which function is more appropriate for reading a multi word string, gets() or scanf()?
gets() function is more appropriate for reading a multi word string, it collects a string of
characters terminated by a new line from the standard input stream stdin.

20. Write a c program to copies the contents of one string to another.


#include<string.h>
#include<conio.h>
#include<string.h>
main()
{
char ori[20],dup[20];
clrscr();
printf(“Enter your name:”);
gets(ori);
strcpy(dup,ori);
printf(“original string:%s”,ori);
printf(“duplicate string:%s”,dup);
}

21. Write a c program to reverse of a given string.


#include<string.h>
#include<conio.h>
#include<string.h>
main( )
{
char text1[30];
printf(“ enter the string”);
gets(text1);
printf(“ Reverse string”);
12
puts(strrev(text1));
}

22. What is the use of atoi() function?


C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into integer
value by the system.

For eg, if the machine uses the ASCII representation, then,

x = ‘a’; printf(“%d \n”,x); will display the number 97 on the screen.

The C library supports a function that converts a string of digits into their integer values. The
function takes the form x = atoi(string)

23. What is sorting?


Sorting is nothing but storage of data in sorted order, it can be in ascending or descending
order.

24. What is meant by searching? What are its types?


The process of identifying or finding a particular record is called Searching.
 Linear
 Binary

25. What is a null character? What is its use in a string?


A null character is specified as ‘\0’. It is used as a terminator in the string.

26. Give an example for enumerated data type.


An enumerated data type is a set of values represented by identifiers called enumeration
constants. It is user-defined data type and the general format of this data type is

enum name {number1, number2, number3….. number};

In the above format enum is a keyword, name is given by the programmer by the identifier
rules. Number1, number2,…number are the members of enumerated data type
UNIT III POINTERS AND STRUCUTURES
1. Define function.
A function is a self contained program segment (block of statements) that carries out some
specific, well defined task.

2. Mention the steps in using a function.


Providing a prototype (or) function declaration

13
Defining a function (or) function definition
Calling the function (or) function call

3. Distinguish between a user defined function and a library function.


The statements of a user-defined function are written as a part of the program, according to the
programmer’s requirement but library functions are predefined.

4. Explain the use of a return statement.


A function of a return statement is to return a value from the function. Since it is usually placed
at the end of a function, a return statement also terminates the function.

5. Mention the types of parameter passing methods to a function?


 Call by value
 Call by reference

6. Differentiate between call by value and call by reference.

Call by Value Call by Reference


In this the value of actual parameter is In this, instead of passing the value, the
passed to formal parameter when we call address of variable is passed. In the
the function, but actual parameters are not function, the address of the argument is
changed. copied into a memory location instead of
the value and the de-referencing operator
is used to access the variable in called
function.

7. What is meant by actual and formal parameters?


 When a function is called by some parameters written within parenthesis. These are
known as actual parameters.
 Formal parameters are those which are written in the function header.

8. Mention the uses of function.


 Modular programming
14
 Reduction in the amount of work and development
 Program and function debugs is easier
 Division of work is simplified due to the use of divide-and-conquer principle
 Reduction in size of the program due to code reusability

9. Mention the categories of function.


 Function with no arguments and no return values.
 Function with arguments and no return values.
 Function with argument and return values.
 Function with no arguments and returns a value.

10. What is recursion?


Recursion is a process by which a function calls itself repeatedly until some specified condition
has been satisfied.

11. Difference between recursion and iteration.


S.No Recursion Iteration
Recursion achieves repetition through Iteration explicitly a repetition
1
repeated function calls. structures.
Recursion terminates when a base case Iteration terminates when the loop
2
to recognized. continuation test becomes false.
An infinite loop occurs if the recursion An infinite loop occurs when the
step does not reduce the that problem loop continuation test never become
3
each time in a manner that coverage on false
the base case
Recursion causes another copy of the Iteration normally occurs within a
4 function and hence a considerable loop so the extra memory
memory space is occupied assignment is omitted.

12. What is the purpose of main()?


The purpose of the main() function is to identify the beginning of the program. The C compiler
always starts its execution of a C program from the main() function.

13. What is a pointer variable? (or) what is a pointer?


Pointer is a variable which stores the address of another variable.
Eg: int *p;
int x;
p=&x;
x=5;

14. List out any two uses of pointers. (or) Mention some of the advantages of pointers
15
 Pointers reduce the length and completing of the program
 Pointers improve the efficiency of certain routines
 It supports dynamic memory allocation
 It provides functions which can modify their calling arguments

15. What do you mean by dynamic memory allocation?


Dynamic memory allocation is a process by which, the required memory address is obtained
without an explicit declaration. The required memory space is obtained by using memory
allocation functions like malloc() and calloc(). Thus the required memory space is dynamically
created and assigned.

16. What is the use of malloc()?


The malloc() function is used to allocate a contiguous block of memory in bytes and returns the
starting address of the memory through the pointer variable.

17. What is the difference between the indirection operator and the address of operator?
The indirection operator(*) returns the value of the address stored in a pointer. The address of
operator(&) returns the memory address of the variable.

18. Mention the arithmetic operators used with pointer variables.


+, -, ++, --

19. Mention some of the library functions dealing with memory allocation.
The library functions dealing with memory allocation are malloc(), calloc(), realloc() and
free().

20. What is the difference between array and pointer?


S.No. Array Pointer
It belongs to static memory allocation
It belongs to dynamic memory
1
allocation
Memory is allocated during compile Memory is allocated during run time
2
time
3 Memory allocation is fixed Memory allocation is variable
4 Memory is wasted Memory is conserved

21. What is meant by pointer to pointer?


A pointer variable that points to another pointer variable is known as pointer to pointer.
Eg:
int *p1,**p2,v=35;
p1=&v;
16
p2=&p1;

22. Define an array of pointers.


Whenever addresses are stored as array elements, such an array is called an array of pointers.
Eg: int *a[10];

23. Explain the use of the sizeof() operator.


The use of the sizeof() operator gives the size of the memory for the data type or variable. Eg:
sizeof(float) will give 4 bytes.

24. State the equivalent pointer declaration of the array declaration char a[10];
The equivalent pointer declaration is char *a[];

25. What does the error ‘Null Pointer Assignment’ means and what causes this error?
As null pointer points to nothing so accessing a uninitialized pointer or invalid location may
cause an error.

26. What is a Structure?


Structure is a group name in which dissimilar data’s are grouped together.
Eg:
struct stud
{
int rno;
char name[20];
int marks;
}s1;

27. What is the difference between a structure and a union?

S.No. Structure Union


In a structure every member has its All the members of a union use the
1 own memory space same memory space to store the
values
The keyword struct is used It follows the same syntax as
2 structure except that the keyword
union is used in place of struct
It can handle all the members or a It can handle only one member at a
3 few as required at a time time, as the same space is used by
all the members
4 A structure may be initialized with Only the first members may be
17
all its members initialized
5 More storage is required Conservation of memory is possible

28. How is a structure different from an array?


A structure is a heterogeneous data type whereas an array is a homogeneous data type.

29. What is meant by a member or a field of a structure?


The data items enclosed within a structure are known as members or fields and they can be of
the same or different data types.

30. What is meant by initialization of a structure?


Structure variables can be initialized at the point of their definition. Consider the following
structure declaration
struct stud
{
int rno;
char name[20];
char branch[10];
int marks;
};
A variable of the structure student can be initialized during its definition as follows:
stud s1={5,”AAA”,”IT”,450};

31. What is meant by an array of structure?


A group of structures may be organized in an array resulting in an array of structures. Each
element in the array is a structure.
struct emp
{
char ename[20];
int eno;
};
struct emp e[5];
which defines an array of 5 structures.

32. What is meant by a nested structure?


If a structure contains one or more structures as its members, it is known as a nested structure.

33. Define a self-referential structure.


In a structure, if one or more members are pointers to the same structure, then this structure is
known as a self referential structure.

18
34. What is meant by a union? Give example.
A union is a data type in ‘C’ which allows overlay of more than one variable in the same
memory area.
Example:
union emp
{
char name[20];
char eno[10];
}
union emp e1;

35. What is the use of typedef?


It allows the user to define an identifier that represent an existing data type. The general syntax
of typedef is
typedef type identifier;

Example
typedef int units;
units a,b,c; is equivalent to int a,b,c;

37. Differentiate between array and structures.

S.No. Arrays Structures


An array is a single entity A structure is a single entity
1 representing a collection of data representing a collection of data items
items of same data type of different data type
A structure may have a declaration
2 An array has declaration only
followed by a definition
The declaration describes the
An array declaration reserves prototype of the structure and the
3 enough memory space to store the definition tells the compiler to reserve
values of its elements enough memory space to store the
values of its members
An array size is known at the time The members and their data types are
4
of declaration known at the time of declaration
There is no keyword to mention the The keyword struct tells the compiler
5 array data type. An identifier that it is a struct data type
ending with [] is an array
38. What is meant by pointer to structure? Give example.
A pointer to a structure is similar to a pointer to an ordinary variable. It is created in the same
way that a pointer to an ordinary variable is created.

19
Example:
struct stud
{
int rno;
char name[20];
};
struct stud *s1;

39. What is meant by dynamic memory allocation?


Dynamic memory allocation is a process by which required memory address is obtained
without an explicit declaration. The required memory space is obtained by using the memory
allocation functions like maloc() and calloc(). Thus the required memory space is dynamically
created and assigned.

40. Difference between static memory allocation and dynamic memory allocation.
S.No. Static memory allocation Dynamic memory allocation
Memory is allocated before the Memory is allocated during the
1 execution of the program execution of the program
begins
Variables remain permanently Allocated only when program unit
2
allocated is active
Memory cannot be resized after Memory can be dynamically
3
the initial allocation expanded and shrunk as necessary
4 Implemented using stacks Implemented using heap
5 Faster execution Slower execution
Memory cannot be reuse when Memory can be freed when it is no
6 it is no longer needed longer needed and reuse or
reallocate during execution

41. Difference between malloc() and calloc().


S.No. malloc() calloc()
The name malloc stands for The name calloc stands for contiguous
1
memory allocation allocation
2 malloc() allocates memory calloc() allocates the memory and also
block of given size and returns initializes the allocated memory block
20
a pointer to the beginning of the
block. malloc() doesn’t to zero
initialize the allocated memory
calloc() take two arguments those are:
malloc() takes one argument
3 number of blocks and size of each
that is, number of bytes
block
Syntax:
Ptrvariable=(cast_type*)malloc( Ptrvariable=(cast_type*)calloc(blocks
4
size_in_bytes); ,
size_of_blocks);

UNIT IV FILE AND HANDLING SIGNALS AND PROCESS

1. Define file

21
A file is a region of storage on hard disks or an auxiliary storage device such as magnetic tape
or disk where a sequence of data is stored. It contains bytes of information.

2. List the basic operations of files.


Naming a file
Opening a file
Writing data to a file
Reading data from a file
Closing a file

3. Define stream.
A stream is a source or destination data associated with input / output device. Actually stream
is a pointer representing a block to hold data temporarily during the input / output operations.

4. Define text stream.


Text stream is a sequence of lines of text. In this it represents the character in machine
character code (ASCII Code). Here character translation will occur, because of these
translations the character written or read will not be same in the external device.

5. Define Binary stream.


A binary stream is a sequence of unprocessed byte. Here it represents raw data without any
conversion. Here the number of characters written or read will be same because of no character
translation occur.

6. Give the modes in which files can be opened.


The files can be opened under various modes such as
r - Open text file for reading
w - Create a text file for writing
a - Append to text file
rb - Open binary file for reading
wb - Create binary file for writing
ab - Append to a binary file
r+ - Open text file for read/write
w+ - Create text file for read/write
a+ - Open text file for read/write
rb+ or r+b - Open binary file for read/write
wb+ or w+b - Create binary file for read/write
ab+ or a+b - Open binary file for read/write

7. Define Sequential access and Random access file


Sequential access file :
Accessing file content byte by byte. ie file content will be accessed from starting byte
onwards.
22
Random access file:
Accessing the file content randomly. ie We can move the file pointer to desired location.

8. Write the C code segment to open a file for writing.


FILE *fp;
fp=fopen(“hello.txt”, “w”);

9. List the various file read and write functions.


fegtc(), fputc(), fgets(), fputs(), fprintf(), fscanf(), fread(), fwrite(), getw(), putw()

10. Write short notes on fread().


The general syntax of fread()
fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
fread( ) function returns the number of items read. This value may be less than count if the end
of the file is reached or an error occurs.
buffer is a pointer to a region of memory that will receive the data from the file
The value of count determines how many items are read or written, with each item being
num_bytes bytes in length.

11. How will you check end of the file? Give example.
The feof( ) function determines whether the end of the file associated with stream has been
reached. A nonzero value is returned if the file position indicator is at the end of the file; zero is
returned otherwise.

12. Write the syntax of fseek().


Random read and write operations are performed using the C I/O system with the help of fseek(
)
fseek(FILE *fp, long int numbytes, int origin);
origin:
Beginning of file – SEEK_SET
Current position - SEEK_CUR
End of file - SEEK_END

13. Write short note on ftell().


The ftell( ) function returns the current value of the file position indicator for the specified
stream
In the case of binary streams, the value is the number of bytes the indicator is from the
beginning of the file

14. Write a C code segment for file writing.


#include <stdio.h>
main()
{
FILE *fp;
23
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
15. Write a C code segment for file reading.
#include <stdio.h>
main()
{
FILE *fp;
char buff[100];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("%s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("%s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("%s\n", buff );
fclose(fp);
}

16. Write short note on fwrite()


The General syntax fwrite()
fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);

buffer is a pointer to a region of memory that will receive the data from the file. The value of
count determines how many items are read or written, with each item being num_bytes bytes in
length.
17. Write the C code segment to detect error when opening a file.
FILE *fp;
if ((fp = fopen("test", "w"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
18. What are command line arguments in C?
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments.
The command line arguments are handled using main() function arguments where argc refers
to the number of arguments passed, and argv[] is a pointer array which points to each argument
passed to the program

24
19. Is FILE a built-in data type?
No, it is a structure defined in stdio.h.
20. What is difference between file opening mode r+ and w+ in c?
Both r+ and w+ we can read ,write on file but r+ does not truncate (delete) the content of
file as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the
content of file as well as create a new file if such file doesn’t exists.

21. What is the purpose of rewind() ?


The function rewind is used to bring the file pointer to the beginning of the file.
rewind(fp);

Where fp is a file pointer. Also we can get the same effect by feek(fp,0,0);

25

You might also like