bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / assignment-secondary / assignment-s-21.c

assignment-s-21.c (1764B)


      1 /* Write a program to copy the contents of a text file to another file, after removing all
      2 white spaces (spaces, tabs, newlines). */
      3 
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <string.h>
      7 
      8 #define NEW_FILE_PREFIX "cleaned_"
      9 
     10 int cleaning(FILE *);
     11 
     12 int main()
     13 {
     14     char filename[50];
     15     char *newFilename = NULL;
     16     FILE *givenFile = NULL;
     17     FILE *cleanedFile = NULL;
     18     int len, temp;
     19 
     20     printf("Enter the filename (Max: 50 character): ");
     21     fgets(filename, sizeof(filename), stdin);
     22     len = strlen(filename);
     23     if (filename[len - 1] == '\n')
     24     {
     25         filename[len - 1] = '\0';
     26     }
     27 
     28     givenFile = fopen(filename, "r");
     29     if (givenFile == NULL)
     30     {
     31         printf("\nCouldn't opened the file \"%s\""
     32                "\nPlease ensure that \"%s\" is in the same folder.",
     33                filename, filename);
     34         return 1;
     35     }
     36 
     37     len += strlen(NEW_FILE_PREFIX);
     38     newFilename = (char *)malloc((len + 1) * sizeof(char));
     39     if (newFilename == NULL)
     40     {
     41         printf("\nMemory allocation failed.");
     42         fclose(givenFile);
     43         return 1;
     44     }
     45     newFilename[0] = '\0';
     46     strcat(newFilename, NEW_FILE_PREFIX);
     47     strcat(newFilename, filename);
     48 
     49     cleanedFile = fopen(newFilename, "w");
     50     if (cleanedFile == NULL)
     51     {
     52         printf("\nCUnable to create the file \"%s\"", newFilename);
     53         free(newFilename);
     54         return 1;
     55     }
     56 
     57     while ((temp = fgetc(givenFile)) != EOF)
     58     {
     59         if (temp != ' ' && temp != '\n' && temp != '\t')
     60         {
     61             fputc(temp, cleanedFile);
     62         }
     63     }
     64 
     65     printf("\nSuccessfully cleaned: \"%s\"", filename);
     66     printf("\nGenerated file: \"%s\"", newFilename);
     67 
     68     fclose(givenFile);
     69     fclose(cleanedFile);
     70     free(newFilename);
     71 
     72     return 0;
     73 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror