Thursday , August 17 2017
Home / C / C program to remove extra blank spaces from a file

C program to remove extra blank spaces from a file

Many a times is happens that when you copy content from a incompatible source then extra spaces are added which is due to mismatched format. To get rid of this here is program in c to remove extra blank spaces from a file.. In this content of a file are added to a new file named newfile.txt which contains content with removed extra blank spaces.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp,*fp2;
    int p;
    char *filename;
            printf("enter the file name from which you have to remove the extra blank spaces: ");
            scanf("%s",filename);
            printf("%s",filename);
            fp=fopen(filename,"r");
            fp2=fopen("newfile.txt","w");  //all the content gets copied to this filename and extra blank spaces are also removed from your file

            while((p=getc(fp))!=EOF)
            {

                fputc(p,fp2);
                if (p==32) // since the ascii code for a blank space is 32
                    {
                              while((p=getc(fp))==32)
                              {
                              }
                    fputc(p,fp2);
                    }
            }

fclose(fp);
fclose(fp2);
getch();
return 1;
}

Tags: C program to remove blank spaces from a file, C program to remove extra blank spaces from a text file.

Check Also

How to Solve Linear Equation in One Variable In C Programming?

C Program to Solve any Linear Equation in One Variable Find complete C program to ...

4 comments

  1. This program is about deleting the extra blank spaces from the file,
    how can I modify it to delete all the blank spaces from the file ???
    Reply ASAP

  2. How can I modify this program to delete all the blank spaces from the file?

    • Hi Udayan You simply modify the inner while loop to remove all blank spaces from a file:

      while((p=getc(fp))!=EOF)
      {

      fputc(p,fp2);
      if (p!=32) // this will now skip the blank spaces
      {
      fputc(p,fp2); // this will add up all non-blank spaces to fp2 file
      }
      }

      The code below will remove blank spaces appearing together i.e removing consecutive and repetitive blank spaces
      while((p=getc(fp))==32)
      {
      }
      by simply skipping this part your query will be solved

      • I compiled above code but it has no effect

        I have placed two space between two words and it does not remove space

        I am using turboC4

        is there any other way?

Leave a Reply

Your email address will not be published. Required fields are marked *