Advertisement
FILE *fopen(const char *filename, const char *mode)
File Mode | Description |
---|---|
"r" | Searches for the file and opens it in read mode(if the file is found). If the file is not found, NULL is returned and no new file is created. |
#include<stdio.h>
int main()
{
/* this will find the file in the directory where this C program file is stored */
FILE *fp = fopen("File1.txt", "r"); /* r = read-only mode */
char ch;
int tab = 0;
int space = 0;
int character = 0;
int newline = 0;
while(2)
{
ch = fgetc(fp);
if(ch == 't')
{
tab = tab + 1;
}
if(ch == '\n')
{
newline = newline + 1;
}
if(ch == ' ')
{
space = space + 1;
}
if(ch == EOF)
{
break;
}
printf("ch : %c \n", ch);
character = character + 1;
}
/*Closing the file after reading is completed */
fclose(fp);
printf("The total number of characters in a file : %d ", character);
printf("The total number of tabs in a file : %d ", tab);
printf("The total number of newline in a file : %d ", newline);
printf("The total number of spaces in a file : %d ", space);
}
The total number of characters in a file : 95
The total number of tabs in a file : 4
The total number of newline in a file : 3
The total number of spaces in a file : 14
Advertisement
FILE *fp = fopen("C:\\Users\\Admin\\Desktop\\C Programs\\File2.txt", "r");
#include<stdio.h>
#include<stdlib.h>
int main()
{
/* this will find the file in the directory where this C file is stored */
FILE *fp = fopen("File2.txt", "r"); /*Let's say this file doesn't exist on disk */
char ch;
int tab = 0;
int space = 0;
int character = 0;
int newline = 0;
/* This if block will be executed, if the searched file is not found */
if(fp == NULL)
{
printf("Sorry, the file that you are looking for, does not exist.");
exit(1);
}
/* If the file is found, this else block will be executed */
else
{
while(1)
{
ch = getc(fp);
if(ch == 't')
{
tab = tab + 1;
}
if(ch == '\n')
{
newline = newline + 1;
}
if(ch == ' ')
{
space = space + 1;
}
if(ch == EOF)
{
break;
}
printf("ch : %c \n", ch);
character = character + 1;
}
}
/* Closing the file being opened for reading */
fclose(fp);
printf("The total number of characters in a file : %d ", character);
printf("\n");
printf("The total number of tabs in a file : %d ", tab);
printf("\n");
printf("The total number of newline in a file : %d ", newline);
printf("\n");
printf("The total number of spaces in a file : %d ", space);
return 0;
}
Sorry, the file that you are looking for, does not exist.
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement