Fenil
Fenil

Reputation: 396

How to remove whitespace from a file in c

I want the file to be without any whitespaces but the code I have tried below I am not sure how do I delete a char so I tried inserting a backspace(non-printable character) but this doesn't seem to work

#include <stdio.h>
int main ()
{
 FILE* fp;
 fp = fopen("in.txt","r+");
 int ch;
 while((ch = getc(fp))!=EOF){
     if( (ch == ' ') || (ch == '\n')){
         fputc(8,fp);
       }

   }
}

The file is

abcd efgh

Is there any working way to do this?, without using a new file (ie.copy all except whitespace)

Upvotes: 0

Views: 1436

Answers (1)

You can't delete a character from the middle of a file.

What you need to do is create a new file, and write all the characters that aren't whitespace to the new file. You can then delete the old file if you want.

Upvotes: 2

Related Questions