C Programming with files  ( Reading and playing with characters of file)

After reading our previous post, you are now ready to play with C Programming with files . Let’s start from counting Character,Tabs , Spaces etc . Let us try our hand to make a program that will read a file and count number of Character, Tabs , Spaces  and newlines to do some hack 😉

#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fp;
char ch;
int nl,nt,nb,nc=0; //intialise number of lines, tabs, blank spaces and characters to 0

fp=fopen(argv[1],"r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
nc++; //to count number of characters
if(ch=='')
nb++; //to count number of blank spaces
if(ch=='\n')
nl++; //to count number of lines
if(ch=='\t')
nt++; //to count number of tabs
}

fclose(fp);
printf("Total number of character in file = %d \n",nc);
printf("Total number of blank spaces in file = %d \n",nb);
printf("Total number of New Lines in file = %d \n",nl);
printf("Total number of tabs in file = %d \n",nt);

printf("\nEnjoy Programming with Buffercode\n");
return 0;
}

Here is it’s Output:

buffer@buffercode:~/Desktop/Buffercode$ gcc -o Buffercode BUFFERCODE.C
buffer@buffercode:~/Desktop/Buffercode$ ./Buffercode BUFFERCODE.C

Total number of character in file = 847
Total number of blank spaces in file = 212
Total number of New Lines in file = 31
Total number of tabs in file = 0

Enjoy Programming with Buffercode

C Programming with files : Counting Character,Tabs, Spaces from files and writing on files

I hope most of the stuff in the program can be easily understood , nothing is new here so after reading from file.

C Programming with files (Writing on files)

Let’s try our hand to write a program on a file..

#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fs, *ft;
char ch;
fs=fopen(argv[1],"r");
if(fs== NULL)
{
  puts("\nCann't open source file , check your file please \n");
  exit(1);
}
ft=fopen(argv[2],"w");
if(ft==NULL)
{
  puts("Cann't open target file, please check it's error");
  fclose(fs); // close connection from fs
  exit(2);
}
while(1)
{
  ch=fgetc(fs);
  if(ch==EOF)
  break;
  else
  fputc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}

Here fputc() function works similar to putch() , in the sense both output characters. Just the diff is putch always write to VDU while fputc writes for FILES .

Enjoy coding with Buffercode , if stuck in any problem in C Programming with files  please ask in comments .

SEE ALSO: Apple’s first Watch-ready apps start appearing on app store,Apple Watch Video — Guided Tour

Follow us on Facebook, Google Plus and Twitter.
Previous