I have made a beginner program using C that uses file handling and formats the given file. Formatting includes removing trailing blank spaces, replacing one or more blanks by a single blank and also wrapping lines. It would be extremely helpful if you could point out the mistakes I have made and also if I add any other features to file formatting.
MAIN.C
#include <stdio.h>
#include <stdlib.h>
#include "whiteSpacing.c"
#include "lineFolding.c"
FILE *p;
FILE *q;
char c;
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Error! Check number of arguements.\n");
exit(-1);
}
p = fopen(argv[1], "r"); //original file containing input
q = fopen("temporary.txt", "w");
if(p == NULL || q == NULL) //error checking, also asks user if file is to be created.
{
printf("ERROR! Unable to open file\n");
printf("Do you want to create '%s' file ? (y/n)\n", argv[1]);
c = getchar();
if(c == 'y' || c == 'Y')
{
p = fopen(argv[1], "w+");
printf("Type here to write to the file\n");
while((c = getchar()) != EOF)
{
putc(c, p);
}
fclose(p);
p = fopen(argv[1], "r");
}
else
exit(1);
}
while((c = getc(p)) != EOF) // for line wrapping
{
folding();
}
fclose(p);
fclose(q);
p = fopen("temporary.txt", "r"); // original file will be overwritten
q = fopen(argv[1], "w");
if(p == NULL || q == NULL)
{
printf("ERROR! Unable to open file\n");
exit(1);
}
while((c = getc(p)) != EOF) //removes trailing spaces/tabs, also replaces two or more white space by a single space.
{
whiteSpacing();
}
remove("temporary.txt");
printf("Text in \"%s\" was formatted and overwritten.\n", argv[1]);
fclose(p);
fclose(q);
return 0;
}
linefolding.c
#define MAXLEN 65 //length for wrapping
#define MAXLINE 1000 // maximum length for one line
extern FILE *p;
extern FILE *q;
extern char c;
int getLine(char *);
void trim(char *);
void folding(void)
{
char line[MAXLINE];
int len;
while((len = getLine(line)) > 1) // proceed only if length of line is greater than 1
{
if(len > MAXLEN) // fold the length only if length of line is greater than the MAXLEN.
{
trim(line);
}
fprintf(q, "%s", line);
}
}
int getLine(char line[])
{
int nc = 0;
while(((c != EOF)) && c != '\n') // store each character of a line in an array.
{
line[nc] = c;
nc++;
c = getc(p);
}
if(c == '\n')
line[nc] = '\n';
line[nc + 1] = '\0';
return nc;
}
void trim(char line[])
{
int i = 0;
int lastBlank = 0;
int j = 1;
for(i = 0; line[i] != '\0'; i++)
{
if(line[i] == ' ' || line[i] == '\t' || line[i] == '\n' || line[i] == ',' || line[i] == '.') // kees track of the last white Spacing or non alphabetical character .
{
lastBlank = i;
}
if(i == MAXLEN * j) //prints a new line at every MAXLEN interval
{
line[lastBlank] = '\n';
j++;
}
}
line[i] = '\n';
line[i + 1] = '\0';
}
whiteSpacing.c
#include <stdio.h>
extern FILE *p;
extern FILE *q;
extern char c;
void whiteSpacing()
{
while(c == ' ') //replaces two or more spaces by a single space
{
c = getc(p);
if (c != ' ' && c != EOF)
putc(' ', q);
}
putc(c, q);
}