C PROGRAM ON FILE HANDLING
C Program to Create a File and Store Information
/*
* C program to create a file called emp.rec and store information
* about a person, in terms of his name, age and salary.
*/
#include <stdio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
/* open for writing */
fptr = fopen("emp.rec", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}
$ cc pgm95.c
$ a.out
Enter the name
raj
Enter the age
40
Enter the salary
4000000
C Program to Count the Number of Lines in Text File
/*
* C Program to Find the Number of Lines in a Text File
*/
#include <stdio.h>
int main()
{
FILE *fileptr;
int count_lines = 0;
char filechar[40], chr;
printf("Enter file name: ");
scanf("%s", filechar);
fileptr = fopen(filechar, "r");
//extract character from file and store in chr
chr = getc(fileptr);
while (chr != EOF)
{
//Count whenever new line is encountered
if (chr == 'n')
{
count_lines = count_lines + 1;
}
//take next character from file.
chr = getc(fileptr);
}
fclose(fileptr); //close file.
printf("There are %d lines in %s in a file\n", count_lines, filechar);
return 0;
}
$ cc pgm49.c
$ a.out
Enter file name: pgm2.c
There are 43 lines in pgm2.c in a file
C Program to Convert the Content of File to Lowercase
/*
* C Program to Convert the Content of File to LowerCase
*/
#include <stdio.h>
#include <errno.h>
int to_lower_file(FILE *);
void main(int argc, char * argv[])
{
int op = -1;
char ch;
FILE *fp;
if (fp = fopen(argv[1], "r+"))
{
printf("FILE has been opened..!!!\n");
op = to_lower_file(fp);
printf(" %d \n", op);
fclose(fp);
}
else
{
perror("Error Occured");
printf(" %d\n ", op);
}
}
int to_lower_file(FILE *f)
{
int c;
char ch;
while ((ch = fgetc(f))! = EOF)
{
c = (int)ch;
if (c >= 65 && c <= 90)
{
ch = ch + 32;
fseek(f, -1L, 1);
fputc(ch, f);
}
}
return 0;
}
$ gcc file4.c
$ cat test1
THE FUNCTION STRERROR RETURNS A POINTER TO AN ERROR MSG STRING WHOSE CONTENTS ARE IMPLEMENTATION DEFINED.
THE STRING IS NOT MODIFIABLE AND MAYBE OVERWRITTEN BY A SUBSEQUENT CALL TO THE STRERROR FUNCTION.
$ ./a.out test1
FILE has been opened..!!!
0
$ cat test1
the function strerror returns a pointer to an error msg string whose contents are implementation defined.
the string is not modifiable and maybe overwritten by a subsequent call to the strerror function.
C Program to Capitalize First Letter of Each Word in a File
/*
* C Program to Capitalize First Letter of every Word in a File
*/
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
int to_initcap_file(FILE *);
void main(int argc, char * argv[])
{
FILE *fp1;
char fp[10];
int p;
fp1 = fopen(argv[1], "r+");
if (fp1 == NULL)
{
printf("cannot open the file ");
exit(0);
}
p = to_initcap_file(fp1);
if (p == 1)
{
printf("success");
}
else
{
printf("failure");
}
fclose(fp1);
}
/* capitalizes first letter of every word */
int to_initcap_file(FILE *fp)
{
char c;
c = fgetc(fp);
if (c >= 'a' && c <= 'z')
{
fseek(fp, -1L, 1);
fputc(c - 32, fp);
}
while(c != EOF)
{
if (c == ' ' || c == '\n')
{
c = fgetc(fp);
if (c >= 'a' && c <= 'z')
{
fseek(fp, -1L, 1);
fputc(c - 32, fp);
}
}
else
{
c = fgetc(fp);
}
}
return 1;
}
$ cc file5.c
$ a.out sample
success
$ cat sample
Wipro Technologies
File Copy Function
Successfully Read
C Program to Replace a Specific Line in a Text File
/*
* C Program to Replace a specified Line in a Text File
*/
#include <stdio.h>
int main(void)
{
FILE *fileptr1, *fileptr2;
char filechar[40];
char c;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filechar);
fileptr1 = fopen(filechar, "r");
c = getc(fileptr1);
//print the contents of file .
while (c != EOF)
{
printf("%c", c);
c = getc(fileptr1);
}
printf(" \n Enter line number to be deleted and replaced");
scanf("%d", &delete_line);
//take fileptr1 to start point.
rewind(fileptr1);
//open replica.c in write mode
fileptr2 = fopen("replica.c", "w");
c = getc(fileptr1);
while (c != EOF)
{
if (c == 'n')
{
temp++;
}
//till the line to be deleted comes,copy the content to other
if (temp != delete_line)
{
putc(c, fileptr2);
}
else
{
while ((c = getc(fileptr1)) != 'n')
{
}
//read and skip the line ask for new text
printf("Enter new text");
//flush the input stream
fflush(stdin);
putc('n', fileptr2);
//put 'n' in new file
while ((c = getchar()) != 'n')
putc(c, fileptr2);
//take the data from user and place it in new file
fputs("n", fileptr2);
temp++;
}
//continue this till EOF is encountered
c = getc(fileptr1);
}
fclose(fileptr1);
fclose(fileptr2);
remove(filechar);
rename("replica.c", filechar);
fileptr1 = fopen(filechar, "r");
//reads the character from file
c = getc(fileptr1);
//until last character of file is encountered
while (c != EOF)
{
printf("%c", c);
//all characters are printed
c = getc(fileptr1);
}
fclose(fileptr1);
return 0;
}
$ cc pgm48.c
$ a.out
Enter file name: pgm3.c
/*
* C Program to Convert Octal to Decimal
*/
#include <stdio.h>
#include <math.h>
int main()
{
long int octal, decimal = 0;
int i = 0;
printf("Enter any octal number: ");
scanf("%ld", &octal);
while (octal != 0)
{
decimal = decimal +(octal % 10)* pow(8, i++);
octal = octal / 10;
}
printf("Equivalent decimal value: %ld",decimal);
return 0;
}
Enter line number to be deleted and replaced 13 replaced
Enter new text
/*
* C Program to Convert Octal to Decimal
*/
#include <stdio.h>
#include <math.h>
int main()
{
long int octal, decimal = 0;
int i = 0;
replaced
printf("Enter any octal number: ");
scanf("%ld", &octal);
while (octal != 0)
{
decimal = decimal +(octal % 10)* pow(8, i++);
octal = octal / 10;
}
printf("Equivalent decimal value: %ld",decimal);
return 0;
}
C Program to Display the Inventory of Items in a Store
/*
* C program to display the inventory of items in a store / shop
* The inventory maintains details such as name, price, quantity
* and manufacturing date of each item.
*/
#include <stdio.h>
void main()
{
struct date
{
int day;
int month;
int year;
};
struct details
{
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++)
{
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
printf(" ***** INVENTORY ***** \n");
printf("---------------------------------------------------------
---------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE
| MFG.DATE \n");
printf("---------------------------------------------------------
---------\n");
for (i = 0; i < n; i++)
printf("%d %-15s %-d %-5d %-5d
%d/%d/%d \n", i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("---------------------------------------------------------
---------\n");
}
Runtime Test Cases
$ cc pgm60.c
$ a.out
Enter number of items:3
Item name:
pendrive
Item code:
123
Quantity:
6
price:
3000
Manufacturing date(dd-mm-yyyy):
30-9-2012
Item name:
computer
Item code:
124
Quantity:
10
price:
10000
Manufacturing date(dd-mm-yyyy):
30-7-2012
Item name:
optical mouse
Item code:
Quantity:
price:
Manufacturing date(dd-mm-yyyy):
***** INVENTORY *****
------------------------------------------------------------------
S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE
------------------------------------------------------------------
1 pendrive 123 6 3000 30/9/2012
2 computer 124 10 10000 30/7/2012
3 optical 0 0 0 0/0/0
------------------------------------------------------------------
$ a.out
Enter number of items:3
Item name:
pendrive
Item code:
123
Quantity:
6
price:
3000
Manufacturing date(dd-mm-yyyy):
30-9-2012
Item name:
computer
Item code:
124
Quantity:
10
price:
10000
Manufacturing date(dd-mm-yyyy):
30-7-2012
Item name:
Mouse
Item code:
125
Quantity:
10
price:
1500
Manufacturing date(dd-mm-yyyy):
30-6-2012
***** INVENTORY *****
------------------------------------------------------------------
S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE
------------------------------------------------------------------
1 pendrive 123 6 3000 30/9/2012
2 computer 124 10 10000 30/7/2012
3 Mouse 125 10 1500 30/6/2012
------------------------------------------------------------------