assignment-s-21.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 21 Jan 2026
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Write a program to copy the contents of a text file to another file, after removing all white spaces (spaces, tabs, newlines).
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NEW_FILE_PREFIX "cleaned_"
int cleaning(FILE *);
int main()
{
char filename[50];
char *newFilename = NULL;
FILE *givenFile = NULL;
FILE *cleanedFile = NULL;
int len, temp;
printf("Enter the filename (Max: 50 character): ");
fgets(filename, sizeof(filename), stdin);
len = strlen(filename);
if (filename[len - 1] == '\n')
{
filename[len - 1] = '\0';
}
givenFile = fopen(filename, "r");
if (givenFile == NULL)
{
printf("\nCouldn't opened the file \"%s\""
"\nPlease ensure that \"%s\" is in the same folder.",
filename, filename);
return 1;
}
len += strlen(NEW_FILE_PREFIX);
newFilename = (char *)malloc((len + 1) * sizeof(char));
if (newFilename == NULL)
{
printf("\nMemory allocation failed.");
fclose(givenFile);
return 1;
}
newFilename[0] = '\0';
strcat(newFilename, NEW_FILE_PREFIX);
strcat(newFilename, filename);
cleanedFile = fopen(newFilename, "w");
if (cleanedFile == NULL)
{
printf("\nCUnable to create the file \"%s\"", newFilename);
free(newFilename);
return 1;
}
while ((temp = fgetc(givenFile)) != EOF)
{
if (temp != ' ' && temp != '\n' && temp != '\t')
{
fputc(temp, cleanedFile);
}
}
printf("\nSuccessfully cleaned: \"%s\"", filename);
printf("\nGenerated file: \"%s\"", newFilename);
fclose(givenFile);
fclose(cleanedFile);
free(newFilename);
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70