w3resource

C Programming: Remove the spaces between two words of its content


29. Remove Spaces from File Content

Write a program in C to read a file and remove the spaces between two words of its content.

C Programming: Remove the spaces between two words of its content


Sample Solution:

C Code:

#include<stdio.h>
#include<ctype.h>

int main() {
    FILE * pfile; // File pointer to handle file operations
    int a; // Variable to store characters read from the file

    printf("\n Remove the spaces between two words :\n");
    printf("-----------------------------------------\n");

    // Open a file named "file.txt" in read mode
    pfile = fopen("file.txt", "r");

    printf(" The content of the file is :\n The quick brown fox jumps over the lazy dog\n\n");

    printf(" After removing the spaces the content is : \n");

    // Check if file is opened successfully
    if (pfile) {
        // Read characters from file until End of File (EOF) is reached
        do {
            a = fgetc(pfile); // Read a character from the file

            // Check if the character is printable (not a space or control character)
            if (isgraph(a)) {
                putchar(a); // Print the character if it's not a space or control character
            }
        } while (a != EOF); // Repeat until End of File (EOF) is encountered

        fclose(pfile); // Close the file
    }

    printf("\n\n");
    return 0; // Return 0 to indicate successful execution of the program
}

Output:

 Remove the spaces between two words  :                                 
-----------------------------------------                               
 The content of the file is :                                           
 The quick brown fox jumps over the lazy dog                            
                                                                        
 After removing the spaces the content is :                             
Thequickbrownfoxjumpsoverthelazydog

Flowchart:

Flowchart: Remove the spaces between two words of its content


For more Practice: Solve these Related Problems:

  • Write a C program to read content from a file and remove all spaces between words before printing.
  • Write a C program to open a text file, strip out all whitespace characters, and display the continuous string.
  • Write a C program to process a file’s content, remove spaces, and then write the modified text to a new file.
  • Write a C program to read a file and merge all words into one long string by eliminating every space.

Go to:


PREV : Check Lowercase Letter.
NEXT : Check Digit Character.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.