Ivth Unit - Files in C
Ivth Unit - Files in C
Variable length argument list, file access including FILE structure, fopen, stdin, sdtout and stderr,
Error Handling including exit, perror and error.h, Line I/O, related miscellaneous functions.
STANDARD I/O
The following library functions implement a simple model of text input and output.
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed it to
the program as per requirement. When we say Output, it means to display some data on screen, printer, or in
any file.
The file pointers are the means to access the file for reading and writing purpose. This section explains how to
read values from the screen and how to print the result on the screen.
1.getchar()
This function is used to read a single character from the standard input (usually the keyboard). It waits for the
user to input a character and returns that character as an integer.
syntax:
int getchar(void);
getchar() function does not take any parameters. The input from the standard input is read as an unsigned char
and then it is typecast and returned as an integer value(int).
syntax
Example program-putchar()
#include <stdio.h>
int main( )
{
char c;
printf( "Enter a character :");
c = getchar( );
printf("%c\n", c);
printf( "\nYou entered: ");
putchar(c);
return 0;
}
output
Enter a character :$
$
You entered: $
3.gets() function:
C library facilitates a special function to read a string from a user. This function is represented as gets() function
and is defined in the <stdio.h> header file of C. gets() function is used to read the string (sequence of characters)
from keyboard input. The function returns a pointer to the string where input is stored.
syntax
OUTPUT
Enter a string: WELCOME
string is: WELCOME
4.puts() function:
C library also facilitates a special function to print a string on the console screen. This function is represented as
puts() function and is also defined in the <stdio.h> header file of C. The return value of the puts function
depends on the success/failure of its execution. On success, the puts() function returns a non-negative value.
Otherwise, an End-Of-File (EOF) error is returned.
syntax
5 %ld long int Used for I/O long signed integer value
Syntax
Example
#include <stdio.h>
int main()
{
int a;
a = 20;
printf("%d", a);
return 0;
}
Output
20
Example
#include <stdio.h>
int main()
{
// Displays the string written inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string
2. scanf():
In C, scanf() is a built-in function for reading user input from the keyboard. It can read values of various data
types like integers, floats, characters, and strings. scanf() is a pre-defined function declared in
the <stdio.h> header file. It uses the & (address-of operator) to store user input in the memory location of a
variable.
Syntax
scanf(“format specifier”, &var1, &var2, …., &varn);
Example-scanf()
#include <stdio.h>
int main()
{
int num1;
printf("Enter a integer number: ");
scanf("%d", &num1);
printf("You have entered %d", num1);
return 0;
}
Output
Enter a integer number: 56
You have entered 56
1.Output of integer numbers –printf()
It is possible to force the printing to be left –justified by placing a minus sign directely after the %
character as shown in fourth example.
It is also possible to pad with zeros the leading blanks by placing a 0 before the field width specifier
in the last item above.
The minus(-) and zero(0) are known as flags. Long integers may be printed by specifying ld in the
place of d in the format specification. Similarly we may use hd for printing short integers.
example
#include<stdio.h>
void main(void)
{
int m=12345;
long n =987654;
printf("%d\n", m);
printf("%10d\n", m);
printf("%o10d\n", m);
printf("%-10d\n", m);
printf("%10ld\n", n);
printf("%10ld\n", -n);
}
output
12345
12345
3007110d
12345
987654
-987654
2.Output of real numbers-printf()
%w.pf
integer w indicates the minimum number of positions that are to be used for the display of the value
and
the integer p indicates the number of digits to be displayed after the decimal point.
The value, when displayed, is rounded to p decimal places and printed right-justified in the field of
w column.
Leading blanks and trailing zeros will appear as necessary. The default precision is 6 decimal places.
The negative numbers will be printed with minus sign.
following examples illustrate the output of the number y= 98.7654 under different formats
specifications.
Program
#include<stdio.h>
void main()
{
float y=98.7654;
printf("% 7.4f\n", y);
printf("%f\n",y);
printf("7.2f\n", y);
printf("-7.2f\n",y);
printf("07.2f\n",y);
printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n",y);
printf("%e\n",y);
}
Output
98.7654
98.765404
7.2f
-7.2f
07.2f
9.88e+01
-9.8765e+01
9.88e+01
9.876540e+01
3.printing of single character –printf()
A single character can be displayed in a desired position using the format :
%wc
The character will be displayed right-justified in the field of w columns.
We can make left-justified by placing a minus sign before the integer w.
The default value for w is 1.
program
#include<stdio.h>
int main()
{
char a= 'c';
printf("Value of a is: %c", a);
return 0;
}
output
Value of a is: c
The following examples show the effect of variety of specifications in printing a string “NEW DELHI
110001” containing 16 characters including blanks.
scanf()
The general form of scanf()
The control sting specifies the field format in which the data is to be entered and the arguments arg1, arg2,
…,argn specify the address of locations where the data is stored. Control string and arguments are separated by
commas.
an input field may be skipped by specifying * in the place of field width. For example the statement
scanf(“%d %*d %d”, &a, &b) will assign the data 123 456 789 as follows:
123 to a , 456 skipped, 789 to b.
example
#include<stdio.h>
void main()
{
int a,b,c,x,y,z;
int p,q,r;
printf("enter 3 integer numbers \n");
scanf("%d %d %d",&a,&b,&c);
printf("%d %d %d \n\n", a,b,c);
printf("Enter two 4-digit numbers\n");
scanf("%4d %4d", &x, &y);
printf("%d %d", x, y);
printf("\n enter two integers\n");
scanf("%d %d", &a,&x);
printf("%d %d\n\n",a,x);
printf("enter a ten digit number \n");
scanf("%3d%4d%3d",&p,&q,&r);
printf("%d %d %d\n\n",p,q,r);}
Output
enter 3 integer numbers
34 56 78
34 56 78
Enter two 4-digit numbers
1234 5678
1234 5678
enter two integers
12 45
12 45
enter a ten digit number
1234567890
123 4567 890
%wf
Here w is an integer number specifying the maximum width of the input data including digits before and after
decimal points and the decimal itself. scanf() reads real number using the simple specifiation %f for both the
notations, namely decimal point notation and exponential notation.
For example the statement
case-1
scanf(“%f %f %f”, &x,&y, &z);
input: 475.89 43.21E-1 678
will assign the value 475.89 to x, 4.321 to y and 678.0 to z. A number may be skipped using %*f specification.
Case-2
When the length of the input data is less than the given width, then the values are stored correctly in the given
variables.
scanf("%3f%4f", &a, &b);
input: 4 1.2
output: 4.000000 1.200000
case-3
scanf("%3f%4f", &a, &b);
input: 1.2 33.1
In this case, the width and length of the input are same, so the values are stored correctly in the variables. i.e a =
1.2 and b = 33.1.
case-4
When the length of input data is greater than the width specified then the values are not stored correctly in the
variables.
As the width of the first variable is 3 only 5.2 is stored in the variable a while 1 is stored in b, and the rest of the
input is ignored.
case-5
case-6
When the length of data is greater than the width specified, then the numbers are printed without any leading
spaces.
printf("a=%5.2f, b=%4.3f", a, b);
input : a = 34189.313 and b = 415.1411.
Output: a=34189.31, b=415.141
We have seen how a single characer can be read from the terminal using getchar function. The same can be
achieved using scanf() function alsos. The scanf fucntion can input strings containing more than one character.
Program
#include<stdio.h>
main()
{
int no;
char name[15];
printf("enter serial number and name one\n");
scanf("%d %15s",&no,name);
printf("%d %15s \n\n", no, name);
}
Output
enter serial number and name one
34
welcome
34 welcome
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
FILE INPUT/OUTPUT IN C
File handling in C stores data of our program in our local store, which can be used at any time because as the
execution of a program completes, our data is lost. Therefore, we need to save our data in any file form - text or
binary files
.We can perform tasks like opening, reading the existing file, writing or adding new content, creating a new file,
closing the file, or even saving the file to a certain location using C.
Types of Files in C
We will be working with two types of files: -
1. Text file
2. Binary file
Text file - The user can create these files easily while handling files in C. It stores information in the form of
ASCII characters internally, and when the file is opened, the content is readable by humans. It can be created by
any text editor with a .txt or .rtf (rich text)extension. Since text files are simple, they can be edited by any text
editor like Microsoft Word, Notepad, Apple Text Edit, etc.
Binary file - It stores information in the form of 0’s or 1’s, and it is saved with the .bin extension, taking less
space. Since it is stored in a binary number system format, it is not readable by humans. Therefore it is more
secure than a text file.
C File Operations
There are different kinds of file operations in C.
1. Creating a new file
2. Opening an existing file
3. Writing data to a file
4. Reading data from an existing file.
5. Moving data to a specific location on the file
6. Closing the file
Now, we will be talking about different file-handling functions to perform file operations in C.
fprintf() Used to write data in existing file fprintf(FILE *stream, const char *format [, argument, ...]);
fscanf() Used to read data from the file fscanf(FILE *stream, const char *format [, argument, ...]);
Function Description Syntax
File Pointer in C
When you want to perform file operations in C like reading from or writing to a file, you need a way to
reference that file within your program. This reference is provided by the file pointer. The file pointer stores the
address of a FILE structure, which contains details about the file, like its name, its current position, its size, etc.
FILE *pointer_name;
FILE is a predefined data type in C, defined in the <stdio.h> header file. It represents a file type.
* indicates that pointer_name is a pointer.
pointer_name can be any valid variable name, and it will become the name of the file pointer.
For example, if you want to declare a file pointer named fptr, you'd write:
FILE *fptr;
fptr = fopen("filename.txt", "r"); //declaration of file pointer
This fptr can then be used with other functions to perform various operations on the file "filename.txt".
Open a File in C
In C, files are opened using the fopen() function. It's one of the fundamental functions for file handling in the C
language.
Syntax of fopen():
FILE *fptr;
fptr = fopen(filename, mode); //declaration of file pointer
Parameters:
filename: A string that represents the name of the file to be opened. It can contain the full path or just
the file name if the file is in the current directory.
mode: A string that specifies the mode in which the file should be opened. The mode can be read,
write, append, etc.
Return Value:
If the file is successfully opened, the fopen() function returns a pointer to the file.
If the file cannot be opened (for example, if the file does not exist or cannot be found), the function
returns a NULL pointer.
w Opens or creates a file for writing. If file exists, its contents are overwritten.
r+ Opens a file for both reading and writing. The file must exist.
w+ Opens a file for both reading and writing. It creates the file if it doesn't exist.
a+ Opens a file for both reading and appending. It creates the file if it doesn't exist.
wb+ Opens or creates a binary file for both reading and writing.
Closing a File :
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.
#include <stdio.h>
void main()
{
FILE *fp; /* Pointer to the file */
char c;
fp= fopen ("C:\\myfiles\\newfile.txt", "r");
while(1) /* Infinite loop –use break to come out of the loop*/
{
c = fgetc(fp);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp);
return 0;
}
Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open a file in “r”
mode, you won’t be able to write the file as “r” is read only mode that only allows reading. This program asks
the user to enter a character and writes that character at the end of the file. If the file doesn’t exist then this
program will create a file with the specified name and writes the input character into the file.
#include <stdio.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("C:\\newfile.txt","w");
if(fp == NULL)
{
printf("Error");
exit(1);
}
printf("Enter any character: ");
scanf("%c", &ch);
/* You can also use fputc(ch, fp);*/
fprintf(fp,"%c",ch);
fclose(fp);
return 0;
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
FILE ACCESS
fprintf() & fscanf() in C programming
fprintf()- It is used to write content or string into a file instead of stdout console.
fscanf()- It is used to read content or string from a file pointed by a file pointer into the stream.
Syntax of fprintf() :
There are various parts of this syntax, they are mentioned below:
stream- It is used to point to the File object that helps to find the stream in which data is to be written.
format- It is used to write a string into the file pointed by the stream pointer.
Output:
The file sample text is open and contains “Welcome to 2023” in its file.
Syntax of fscanf() :
int fscanf(FILE *stream, const char *format, ...);
stream- Its is used to as the file pointer to point where the output will end.
format- Its is used as a string that contains various Format arguments.
Example:
#include<stdio.h>
main()
{
char b[255];
FILE *fp;
fp = fopen(“sample.txt”, “r”);
while(fscanf(fp, “%s”, b)!=EOF)
{
printf(“%s”, b );
}
fclose(fp);
}
Output:
Welcome to 2023
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR HANDLING IN C
C language does not provide any direct support for error handling. However a few methods and variables
defined in errno.h header file can be used to point out error using the return statement in a function. In C
language, a function returns -1 or NULL value in case of any error and a global variable errno is set with the
error code. So the return value can be used to check error while programming.
What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it. It is a global
variable, which can be used to identify which type of error was encountered while function execution, based on
its value. Below we have the list of Error numbers and what does they mean.
C language uses the following functions to represent error messages associated with errno:
perror(): returns the string passed to it along with the textual represention of the current errno value.
strerror() is defined in string.h library. This method returns a pointer to the string representation of
the current errno value.
int main ()
{
FILE *fp;
fp = fopen("Error.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
return 0;
}
output
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
0 or EXIT_SUCCESS: The statements exit(EXIT_SUCCESS) and exit(0) mean that the program has
terminated successfully without any errors or interruptions.
1 or EXIT_FAILURE: The statements exit(1) and exit(EXIT_FAILURE) mean that the program
terminated abruptly with an error.
EXAMPLE-1
#include <stdio.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("C:\\newfile.txt","w");
if(fp == NULL)
{
printf("Error");
exit(1);
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
LINE INPUT AND OUTPUT
The standard library provides an input and output routine fgets that is similar to the getline function.
fgets() reads the next input line (including the newline) from FILE *fp into the character array line; at most
maxline characters will be read. The resulting line is terminated with '\0'. Normally fgets() returns line; on end
of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means
end of file.)
For output, the function fputs() writes a string (which need not contain a newline) to a file:
example-
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char chunk[128];
FILE *fp = fopen("file1.txt", "r");
if(fp == NULL)
{
perror("Unable to open file!");
exit(1);
}
fclose(fp);
}
OUTPUT
Unable to open file!: No such file or directory
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The standard library provides a wide variety of functions. This section is a brief synopsis of the most useful.
More details and many other functions can be found in Appendix B.
String Operations
We have already mentioned the string functions strlen, strcpy, strcat, and strcmp, found in <string.h>. In the
following, s and t are char *'s, and c and n are ints.
strcat(s,t) concatenate t to end of s
strncat(s,t,n) concatenate n characters of t to end of s
strcmp(s,t) return negative, zero, or positive for s < t, s == t, s > t
strncmp(s,t,n) same as strcmp but only in first n characters
strcpy(s,t) copy t to s
strncpy(s,t,n) copy at most n characters of t to s
strlen(s) return length of s
strchr(s,c) find the first occurrence of a character c in a string s
strrchr(s,c) find the last occurrence of a character c in a string s
Ungetc
int ungetc(int c, FILE *fp)
pushes the character c back onto file fp, and returns either c, or EOF for an error.
Command Execution
Storage Management
The functions malloc and calloc obtain blocks of memory dynamically.
void *malloc(size_t n)
returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.
Mathematical Functions
There are more than twenty mathematical functions declared in <math.h>; here are some of the more frequently
used. Each takes one or two double arguments and returns a double.
sin(x) sine of x, x in radians
cos(x) cosine of x, x in radians
exp(x) exponential function ex
log(x) natural (base e) logarithm of x (x>0)
log10(x) common (base 10) logarithm of x (x>0)
pow(x,y) xy
sqrt(x) square root of x (x>0)
fabs(x) absolute value of x
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
VARIABLE LENGTH ARGUMENTS
When we want to have a function, which can take variable number of arguments, i.e., parameters, instead of
predefined number of parameters. The C/C++ programming language provides a solution for this situation and
you are allowed to define a function which can accept variable number of parameters based on your
requirement.
It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just
before the ellipses is always an int which will represent the total number variable arguments passed. To use such
functionality, you need to make use of <stdarg.h> header file which provides the functions and macros to
implement the functionality of variable arguments and follow the given steps −
Define a function with its last parameter as ellipses and the one just before the ellipses is always an int
which will represent the number of arguments.
Create a va_list type variable in the function definition. This type is defined in <stdarg.h> header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro
va_start is defined in <stdarg.h> header file.
Use va_arg macro and va_list variable to access each item in argument list.
Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take the variable number of
parameters and return their average −
int main()
{
printf("Average of 2, 3, 4, 5 = %f”, average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f ", average(3, 5,10,15));
}
Output
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000