Standard I/O devices
Q. WAP to read the information of a file named "[Link]" and write its contents to another
file "[Link]".
#include <stdio.h>
#include <stdlib.h> // For exit()
#include<conio.h>
Void main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "w+");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
getch();
}
[Link] SUBEDI 1
Q. List different types of standard I/O used in C. WAP to write name, roll no and age of five students into a
disk file name "[Link]".
#include <stdio.h>
#include<conio.h>
struct STUDENT
{
char name[20];
int rollno;
int age;
};
void
main()
{
struct STUDENT std[5];
int i;
FILE *fp;
fp = fopen("[Link]", "w");
for(i=0; i<5; i++)
{
printf("Name: ");
scanf("%s",std[i].name);
printf( "Roll: ");
scanf("%d", &std[i].rollno);
printf("Age: ");
scanf("%d", &std[i].age);
fprintf(fp,"Name : %d\tRoll : %d\tAge : %d\n",std[i].name, std[i].rollno, std[i].age);
}
fclose(fp);
getch();
[Link] SUBEDI 2
Q. WAP to continuously read name, age and salary of a worker and write it into a file until user confirms to
end. Then read n from user and display the nth record in the file. Details of worker must be represented by a
structure.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
Void
main()
{
struct WORKER emp;
char next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("[Link]", "w");
do
{
printf("Name: ");
scanf("%s",[Link]);
printf( "Age: ");
scanf("%d", &[Link]);
printf("Salary: ");
scanf("%f", &[Link]);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",[Link], [Link], [Link]);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("[Link]","r");
printf("Enter record number you wanttodisplay : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
}
[Link] SUBEDI 3
Q. WAP to store employee details in a text file. Read data from the text file, sort them in ascending order of
salary and store the sorted record to a binary file. Display the details and rank of employee given by the user.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
int main( )
{
struct WORKER emp; char
next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("[Link]", "w");
do
{
printf("Name: ");
scanf("%s",[Link]);
printf( "Age: ");
scanf("%d", &[Link]);
printf("Salary: ");
scanf("%f", &[Link]);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",[Link], [Link], [Link]);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("[Link]","r");
printf("Enter record number you want to display : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
return 0;
}
[Link] SUBEDI 4
Q. C Program to merge contents of two files into a third file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("[Link]", "r");
FILE *fp2 = fopen("[Link]", "r");
// Open file to store the result
FILE *fp3 = fopen("[Link]", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to [Link]
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to [Link]
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged [Link] and [Link] into [Link]");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
C program to delete a file
#include<stdio.h>
int main() {
if (remove("[Link]") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");
return 0;
}
[Link] SUBEDI 5
Q. Program to count number of characters, words and line in a text file.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fptr;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path : ");
scanf("%s", path);
file=fopen(path,"r");
if(file==NULL)
{
printf("\nUnable to open file.\n");
printf(''Please check if file exists and you have read privilage.\n");
}
characters = words = lines = 0;
while((ch = fgetc(file)) ! = EOF)
{
characters++;
if(ch=='\n' || ch== '\0')
{
lines++;
}
if(ch==' ' || ch==\\t\ || ch=='\n' || ch=='\0')
{
words++;
}
}
if(characters>0)
{
words++;
lines++;
}
printf("\n");
printf("Total characters : %d\n", characters);
printf("Total words : %d\n", words);
printf("Total lines : %d\n", lines);
fclose(file);
return 0;
}
[Link] SUBEDI 6
Q. C Program for Lower Case to Uppercase and vice-versa in a file
#include <stdio.h>
#include <stdlib.h>
void toggleCase(FILE *fptr, const char *path);
int main()
{
/* File pointer to hold reference of input file */
FILE *fPtr; char path[100];
printf("Enter path of source file: ");
scanf("%s", path);
fPtr = fopen(path, "r");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
toggleCase(fPtr, path);
printf("\nSuccessfully converted characters in file from uppercase to lowercase and vice versa.\n");
return 0;
}
/**
* Function to convert lowercase characters to uppercase
* and uppercase to lowercase in a file.
*/
void toggleCase(FILE *fptr, const char *path)
{
FILE *dest;
char ch
// Temporary file to store result
dest = fopen("[Link]", "w"); //
If unable to create temporary file
if (dest == NULL)
{
printf("Unable to toggle case.");
fclose(fptr);
exit(EXIT_FAILURE);
}
/* Repeat till end of file. */
while ( (ch = fgetc(fptr)) != EOF)
{
/*
* If current character is uppercase then toggle
* it to lowercase and vice versa.
*/
[Link] SUBEDI 7
if (isupper(ch))
ch = tolower(ch);
else if (islower(ch))
ch = toupper(ch);
// Print toggled character to destination file.
fputc(ch, dest);
}
/* Close all files to release resource */
fclose(fptr);
fclose(dest);
/* Delete original source file */
remove(path);
/* Rename temporary file as original file */
rename("[Link]", path);
}
Q. C program to replace a specific line with another in a file.
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
int main()
{
/* File pointer to hold reference of input file */
FILE * fPtr;
FILE * fTemp;
char path[100];
char buffer[BUFFER_SIZE];
char newline[BUFFER_SIZE];
int line, count;
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter line number to replace: ");
scanf("%d", &line);
/* Remove extra new line character from stdin */
fflush(stdin);
printf("Replace '%d' line with: ", line);
fgets(newline, BUFFER_SIZE, stdin);
/* Open all required files */
fPtr = fopen(path, "r"); fTemp =
fopen("[Link]", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
[Link] SUBEDI 8
/*
* Read line from source file and write to destination
* file after replacing given line.
*/
count = 0;
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
count++;
/* If current line is line to replace */
if (count == line)
fputs(newline, fTemp);
else
fputs(buffer, fTemp);
}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temporary file as original file */
rename("[Link]", path);
printf("\nSuccessfully replaced '%d' line with '%s'.", line, newline);
return 0;
}
Q. C program to find and replace all occurrences of a word in file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
/* Function declaration */
void replaceAll(char *str, const char *oldWord, const char *newWord);
int main()
{
/* File pointer to hold reference of input file */
FILE * fPtr;
FILE * fTemp;
char path[100];
char buffer[BUFFER_SIZE];
char oldWord[100], newWord[100];
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter word to replace: ");
scanf("%s", oldWord);
printf("Replace '%s' with: ");
scanf("%s", newWord);
/* Open all required files */
fPtr = fopen(path, "r");
fTemp = fopen("[Link]", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
[Link] SUBEDI 9
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
/*
* Read line from source file and write to destination
* file after replacing given word.
*/
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
// Replace all occurrence of word from current line
replaceAll(buffer, oldWord, newWord);
// After replacing write it to temp file.
fputs(buffer, fTemp);
}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temp file as original file */
rename("[Link]", path);
printf("\nSuccessfully replaced all occurrences of '%s' with '%s'.", oldWord, newWord);
return 0;
}
/**
* Replace all occurrences of a given a word in string.
*/
void replaceAll(char *str, const char *oldWord, const char *newWord)
{
char *pos, temp[BUFFER_SIZE];
int index = 0;
int owlen;
owlen = strlen(oldWord);
/*
* Repeat till all occurrences are replaced.
*/
while ((pos = strstr(str, oldWord)) != NULL)
{
// Bakup current line
strcpy(temp, str);
// Index of current found word
index = pos - str;
// Terminate str after word found index
str[index] = '\0';
// Concatenate str with new word
strcat(str, newWord);
[Link] SUBEDI 10
// Concatenate str with remaining words after
// oldword found index.
strcat(str, temp + index + owlen);
}
}
Q. C program to count occurrences of all words in a file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORDS 1000
int main() {
FILE *fptr;
char path[100];
int i, len, index, isUnique;
// List of distinct words
char words[MAX_WORDS][50];
char word[50];
// Count of distinct words
int count[MAX_WORDS];
/* Input file path */
printf("Enter file path: ");
scanf("%s", path);
/* Try to open file */
fptr = fopen(path, "r");
/* Exit if file not opened successfully */
if (fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read previleges.\n");
exit(EXIT_FAILURE);
}
// Initialize words count to 0
for (i=0; i<MAX_WORDS; i++)
count[i] = 0;
index = 0;
while (fscanf(fptr, "%s", word) != EOF)
{
// Convert word to lowercase
strlwr(word);
// Remove last punctuation character
len = strlen(word);
if (ispunct(word[len - 1]))
word[len - 1] = '\0';
// Check if word exits in list of all distinct words
isUnique = 1;
for (i=0; i<index && isUnique; i++)
{
[Link] SUBEDI 11
if (strcmp(words[i], word) == 0)
isUnique = 0;
}
// If word is unique then add it to distinct words list
// and increment index. Otherwise increment occurrence
// count of current word.
if (isUnique)
{
strcpy(words[index], word);
count[index]++;
index++;
} else
{
count[i - 1]++;
}
}
// Close file
fclose(fptr);
/*
* Print occurrences of all words in file.
*/
printf("\nOccurrences of all distinct words in file: \n");
for (i=0; i<index; i++)
{
/*
* %-15s prints string in 15 character width.
* - is used to print string left align inside
* 15 character width space.
*/
printf("%-15s => %d\n", words[i], count[i]);
}
return 0;
}
[Link] SUBEDI 12
Q. C program to count occurrences of a word in file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
/* Function declarations */ int
countOccurrences(FILE *fptr, const char *word);
int main() {
FILE *fptr;
char path[100];
char word[50];
int wCount;
/* Input file path */
printf("Enter file path: ");
scanf("%s", path);
/* Input word to search in file */
printf("Enter word to search in file: ");
scanf("%s", word);
/* Try to open file */
fptr = fopen(path, "r");
/* Exit if file not opened successfully */
if (fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
// Call function to count all occurrence of word
wCount = countOccurrences(fptr, word);
printf("'%s' is found %d times in file.", word, wCount);
// Close file
fclose(fptr);
return 0; }
/**
* Returns total occurrences of a word in given file.
*/
int countOccurrences(FILE *fptr, const char *word)
{
char str[BUFFER_SIZE];
char *pos; int index,
count; count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
[Link] SUBEDI 13
// Index of word in str is //
Memory address of pos - memory //
address of str.
index = (pos - str) + 1;
count++;
}
}
returncount;
}
Q. C program to delete specific line from a file.
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
/* Function declarations */
void deleteLine(FILE *srcFile, FILE *tempFile, const int line);
void printFile(FILE *fptr);
int main() {
FILE *srcFile;
FILE *tempFile;
char path[100];
int line;
/* Input file path and line number */
printf("Enter file path: ");
scanf("%s", path);
printf("Enter line number to remove: ");
scanf("%d", &line);
/* Try to open file */
srcFile = fopen(path, "r");
tempFile = fopen("[Link]", "w");
/* Exit if file not opened successfully */
if (srcFile == NULL || tempFile == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
printf("\nFile contents before removing line.\n\n");
printFile(srcFile);
// Move src file pointer to beginning
rewind(srcFile);
// Delete given line from file.
deleteLine(srcFile, tempFile, line); /*
Close all open files */
fclose(srcFile);
fclose(tempFile);
/* Delete src file and rename temp file as src */
remove(path);
rename("[Link]", path);
printf("\n\n\nFile contents after removing %d line.\n\n", line);
[Link] SUBEDI 14
// Open source file and print its contents
srcFile = fopen(path, "r");
printFile(srcFile);
fclose(srcFile);
return 0;
}
/**
* Print contents of a file.
*/
void printFile(FILE *fptr)
{
charch;
while((ch = fgetc(fptr)) != EOF)
putchar(ch);
}
/**
* Function to delete a given line from file.
*/
void deleteLine(FILE *srcFile, FILE *tempFile, const int line)
{
char buffer[BUFFER_SIZE];
int count = 1;
while ((fgets(buffer, BUFFER_SIZE, srcFile)) != NULL)
{
/* If current line is not the line user wanted to remove */
if (line != count)
fputs(buffer, tempFile);
count++;}
}
[Link] SUBEDI 15
Q. C program to delete a word from file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
void removeAll(char* str, const char * toRemove);
int main() {
FILE * fPtr;
FILE * fTemp;
char path[100];
char toRemove[100];
char buffer[1000];
/* Input source file path path */
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter word to remove: ");
scanf("%s", toRemove);
/* Open files */
fPtr = fopen(path, "r");
fTemp = fopen("[Link]", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
/*
* Read line from source file and write to destination
* file after removing given word.
*/
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
// Remove all occurrence of word from current line
removeAll(buffer, toRemove);
// Write to temp file
fputs(buffer, fTemp);
}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temp file as original file */
rename("[Link]", path);
printf("\nAll occurrence of '%s' removed successfully.", toRemove);
return 0;
}
/**
[Link] SUBEDI 16
* Remove all occurrences of a given word in string.
*/
void removeAll(char * str, const char * toRemove)
{
int i, j, stringLen, toRemoveLen;
int found;
stringLen = strlen(str);
// Length of string
toRemoveLen = strlen(toRemove);
// Length of word to remove
for(i=0; i <= stringLen - toRemoveLen; i++)
{
/* Match word with string */
found = 1;
for(j=0; j < toRemoveLen; j++)
{
if(str[i + j] != toRemove[j])
{
found = 0;
break;
}
}
/* If it is not a word */
if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0')
{
found = 0;
}
/*
* If word is found then shift all characters to left
* and decrement the string length
*/
if(found == 1)
{
for(j=i; j <= stringLen - toRemoveLen; j++)
{
str[j] = str[j + toRemoveLen];
}
stringLen = stringLen - toRemoveLen;
// We will match next occurrence of word from current index.
i--;
}
}
}
[Link] SUBEDI 17
Q. Write a C program to read numbers from a file and write even, odd and prime numbers in separate files.
#include <stdio.h>
int main() {
FILE *fp1, *fp2, *fp3, *fp4;
int n, i, num, flag = 0;
/* open [Link] in read mode */
fp1 = fopen("[Link]", "w");
printf("Enter the value for n:");
scanf("%d", &n);
for (i = 0; i <= n; i++)
fprintf(fp1, "%d ", i);
fprintf(fp1, "\n");
fclose(fp1);
/* open files to write even, odd and prime nos separately */
fp1 = fopen("[Link]", "r");
fp2 = fopen("[Link]", "w");
fp3 = fopen("[Link]", "w");
fp4 = fopen("[Link]", "w");
fprintf(fp2, "Even Numbers:\n");
fprintf(fp3, "Odd Numbers:\n");
fprintf(fp4, "Prime Numbers:\n");
/* print even, odd and prime numbers in separate files */
while (!feof(fp1)) {
fscanf(fp1, "%d", &num);
if (num % 2 == 0) {
fprintf(fp2, "%d ", num);
} else
{
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = 1;
break;
}
} if (!flag)
{
fprintf(fp4, "%d ", num);
}
}
fprintf(fp3, "%d ", num);
flag = 0;
}
}
/* close all opened files */
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
return 0;
}
[Link] SUBEDI 18