L-33 MCS 275 Mon 2 Apr 2001
Below are the programs we discussed in class.
/* L-33 MCS 275 Mon 2 Apr 2001 : double spacing a file, graceful fopen */
#include <stdio.h>
void double_space ( FILE *ifp, FILE *ofp );
/* copies the content of the file ifp into the file ofp,
duplicating every newline character */
void prn_info ( char *progname );
/* prints information on how to use the program */
FILE *open_input_file ( char *name );
/* tries to open the file with the given name for input;
if failure, then the user will be asked to retry */
FILE *open_output_file ( char *name );
/* checks whether the file with the given name already exists;
if the user gives not permission to overwrite, then a new
file name is asked */
int main ( int argc, char **argv )
{
FILE *ifp, *ofp;
if (argc != 3)
{
prn_info(argv[0]); /* print error message */
exit(1);
}
else
{
ifp = open_input_file(argv[1]); /* open for reading */
ofp = open_output_file(argv[2]); /* open for writing */
double_space(ifp,ofp); /* double newline symbols */
fclose(ifp); /* close input file */
fclose(ofp); /* close output file */
return 0;
}
}
void double_space ( FILE *ifp, FILE *ofp )
{
int c; /* integer because of EOF symbol */
while ((c = getc(ifp)) != EOF)
{
putc(c, ofp);
if (c == '\n')
putc('\n', ofp); /* duplicate newline symbol */
}
}
void prn_info ( char *progname )
{
fprintf(stderr,"\n%s%s%s\n\n%s\n\n",
"Usage : ", progname, " infile outfile",
"Double-spaces content of infile into outfile.");
}
FILE *open_input_file ( char *name )
{
FILE *infile;
char work[80]; /* work space for new names */
strcpy(work,name);
infile = fopen(work,"r");
while (infile == NULL)
{
printf("%s\"%s\"%s\n",
"File ", work, " could not be opened. Please try again...");
printf("Give name of the input file : ");
scanf("%s", work);
infile = fopen(work,"r");
}
return infile;
}
FILE *open_output_file ( char *name )
{
FILE *infile, *outfile;
char newname[80];
char answer;
infile = fopen(name,"r"); /* test whether file exists */
if (infile == NULL)
outfile = fopen(name,"w");
else
{
printf("%s\"%s\"%s",
"There is already a file ", name, ". Overwrite ? (y/n) ");
answer = getchar();
if (answer == '\n') /* skip leading new line symbol */
answer = getchar();
if (answer == 'y')
outfile = fopen(name,"w"); /* overwrite existing file */
else
{
printf("Give name of the output file : ");
scanf("%s", newname);
outfile = open_output_file(newname); /* recursion */
}
}
return outfile;
}