Assignment 6: File Handling (Text Files)
A file is a container in computer storage devices which is used for storing output or information permanently in the form of a sequence of bytes on the disk.
In C, you can perform various file handling operations like creating a file, deleting a file, opening a file, reading a file or you can even manipulate the data inside of a file. You can also work with the data in your program code by fetching it from a file.
Declaring File pointer
FILE * pointer;
Example:-
FILE *fp;
Opening a File
fopen(“filename”,mode);
where mode = “r”, “w”,
“a”, “r+”, “w+”, “a+”
Example:-
fp=fopen(“a.txt”, “r”);
Checking for successful open
if (pointer==NULL)
Example:-
if(fp==NULL)
exit(0);
Checking for end of file
feof(pointer)
Example:-
if(feof(fp))
printf(“File has ended”);
Closing a File
fclose(pointer);
fcloseall();
Example:-
fclose(fp);
Character I/O
fgetc, fscanf ,fputc, fprintf
Example:-
ch=fgetc(fp);
fscanf(fp, ”%c”,&ch);
fputc(fp,ch);
String I/O
fgets, fscanffputs, fprintf
Example:-
fgets(fp,str,80); fscanf(fp, ”%s”,str);
Reading and writing formatted data
fscanf fprintf
Example:-
fscanf(fp, ”%d%s”,&num,str);
fprintf(fp, “%d\t%s\n”, num, str);
Random access to files
ftell, fseek, rewind
Example:-
fseek(fp,0,SEEK_END);
/* end of file*/
long int size = ftell(fp);
Set A. Write C programs for the following problems.
1. Write a program to accept a file name and a single character. Display the count indicating total number of times character occurs in the file.
#include <stdio.h>
void main()
{
FILE * fp;
char ch,c,fname[20];
int cnt=0;
printf(“Enter the filename : ”);
gets(fname);
printf(“Enter the Character: ”);
scanf("%c",&c);
fp = fopen(fname, “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
while(!feof(fp))
{
ch = fgetc(fp);
if(ch==c)
{
cnt=cnt+1;
}
}
printf("%c is occured %d times in file.",c,cnt);
fclose(fp);
}
3. Write a program to accept a filename and count the number of words, lines and characters in the file.
#include <stdio.h>
int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount, charcount;
// Initialize counter variables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Enter a filename :");
gets(filename);
// Open file in read-only mode
fp = fopen(filename,"r");
// If file opened successfully, then write the string to file
if ( fp )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp)) != EOF) {
// Increment character count if NOT new line or space
if (ch != ' ' && ch != '\n') { ++charcount; }
// Increment word count if new line or space character
if (ch == ' ' || ch == '\n') { ++wordcount; }
// Increment line count if new line character
if (ch == '\n') { ++linecount; }
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failed to open the file\n");
}
printf("Lines : %d \n", linecount);
printf("Words : %d \n", wordcount);
printf("Characters : %d \n", charcount);
getchar();
return(0);
}
Set B. Write C programs for the following problems.
1. Write a program to read integers from a file and write even and odd numbers in separate files.
#include<stdio.h>
main()
{
FILE *fp,*fp1,*fp2;
int c,i;
clrscr();
fp=fopen("data.txt","w");
printf("enter the numbers");
for(i=0;i<10;i++)
{
scanf("%d",&c);
putw(c,fp);
}
fclose(fp);
fp=fopen("data.txt","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((c=getw(fp))!=EOF)
{
if(c%2==0)
putw(c,fp1);
else
putw(c,fp2);
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
while((c=getw(fp1))!=EOF)
printf("%4d",c);
printf("\n\n");
fp2=fopen("odd.txt","r");
while((c=getw(fp2))!=EOF)
printf("%4d",c);
fcloseall();
}
Set A . Write C programs for the following problems.
1. Write a program to accept two filenames as command line arguments. Copy the contents of the file to the second such that the case of all alphabets is reversed.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("source.txt", "r");
if (fp1 == NULL)
{
puts("File does not exist..");
exit(1);
}
fp2 = fopen("target.txt", "w");
if (fp2 == NULL)
{
puts("File does not exist..");
fclose(fp1);
exit(1);
}
while((ch=fgetc(fp1))!=EOF)
{
if(isupper(ch))
{
ch = tolower(ch);
fputc(ch,fp2);
}
else
{
ch = toupper(ch);
fputc(ch,fp2);
}
}
printf("\nFile successfully copied..");
return 0;
}
2. Write a program to accept a filename as command line argument and count the number of words, lines and characters in the file.
#include <stdio.h>
int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount, charcount;
// Initialize counter variables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Enter a filename :");
gets(filename);
// Open file in read-only mode
fp = fopen(filename,"r");
// If file opened successfully, then write the string to file
if ( fp )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp)) != EOF) {
// Increment character count if NOT new line or space
if (ch != ' ' && ch != '\n') { ++charcount; }
// Increment word count if new line or space character
if (ch == ' ' || ch == '\n') { ++wordcount; }
// Increment line count if new line character
if (ch == '\n') { ++linecount; }
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failed to open the file\n");
}
printf("Lines : %d \n", linecount);
printf("Words : %d \n", wordcount);
printf("Characters : %d \n", charcount);
getchar();
return(0);
}
Set B. Write programs to solve the following problems
1. Write a program to accept details of n students (roll number, name, percentage) and write it to a file named “student.txt”. Accept roll number from the user and search the student in the file. Also display the student details having the highest percentage.
#include <stdio.h>
int main(){
char name[50];
int rno,roll,i,n;
double ptage;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter Roll no,Name and Percentage: ",i+1);
scanf("%d%s%f",&rno,name,&ptage);
fprintf(fptr,"%d\t%s\t%f\n",rno,name,ptage);
}
fclose(fptr);
printf("\n ENter Roll no to search ");
scanf("%d",roll);
fptr=(fopen("student.txt","r"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
fprintf(fptr,"%d\t%s\t%f\n",&rno,name,&ptage);
if(rno==roll)
printf(fptr,"Roll no : %d\tName: %s \tPtage=%f \n",rno,name,ptage);
}
return 0;
}
Write a program which accepts a filename and an integer as command line arguments and encrypts the file using the key.
#include <stdio.h>
#include <string.h>
#define MAX 256
int main() {
FILE *fp1, *fp2;
int key, val, ch, i = 0;
char filename[MAX], temp[] = "temp.txt";
/* get the file name from the user */
printf("Enter your file name:");
scanf("%s", filename);
/* open the given file in read mode */
fp1 = fopen(filename, "r");
/* error handling */
if (!fp1) {
printf("Unable to open the input file!!\n");
return 0;
}
/* open the temporary file in write mode */
fp2 = fopen(temp, "w");
/* error handling */
if (!fp2) {
printf("Unable to open the temporary file!!\n");
return 0;
}
/* get the key from the user to create cipher */
printf("Enter the key to create cipher text:");
scanf("%d", &key);
/* converting plain text to cipher text */
while ((ch = fgetc(fp1)) != EOF) {
/* adding key to the ascii value of the fetched char */
val = ch + key;
fprintf(fp2, "%d ", val);
i++;
if (i % 10 == 0) {
fprintf(fp2, "\n");
}
}
/* closing all opened files */
fclose(fp1);
fclose(fp2);
/* open the file containint cipher text in read mode */
fp2 = fopen(temp, "r");
/* printing the cipher text */
printf("\nCipher text for the given plain text:\n");
while (!feof(fp2)) {
fscanf(fp2, "%d", &ch);
if (!feof(fp2)) {
printf("%c", ch);
}
}
/* moving the file pointer to the start of file */
rewind(fp2);
printf("\n\nConverting the cipher text to plain text:\n");
while (!feof(fp2)) {
fscanf(fp2, "%d", &ch);
if (!feof(fp2)) {
val = ch - key;
printf("%c", val);
}
}
printf("\n");
/* close all opened files */
fclose(fp2);
return 0;
printf("\n");
}
A text file contains lines of text. Write a program which removes all extra spaces from the file.
#include<stdio.h>
#include<ctype.h>
int main()
{
FILE * pfile;
int a;
printf("\n Remove the spaces between two words :\n");
printf("-----------------------------------------\n");
// file.txt contain : the quick brown fox jumps over the lazy dog
pfile=fopen ("file.txt","r");
printf(" The content of the file is :\n The quick brown fox jumps over the lazy dog\n\n");
printf(" After removing the spaces the content is : \n");
if (pfile)
{
do {
a = fgetc (pfile);
if ( isgraph(a) ) putchar (a);
} while (a != EOF);
fclose (pfile);
}
printf("\n\n");
return 0;
}
No comments:
Post a Comment