>Try this code out...and get back to me if u got some problem...
I have a problem, several actually but the second is only nitpicking.
>void main(int argc, char *argv[])
I can describe this with one word. Wrong.
>exit(0);
Yes this is nitpicking, but abruptly terminating after an error is only good for student code. If you did this in a real application without saving data then users would be just a little miffed at losing hours of work because the program couldn't open a file.
You also use the exit function without including stdlib.h.
>while((ch=fgetc(fp))!=EOF)
ch is declared as a char, this can break since EOF is an integer value that usually can't be held by a char variable.
Personally, I would have structured it differently to create a better flow. The way your program is (once fixed), it seems like you expect it to fail immediately while a program should expect to succeed but still take appropriate measures in the event that it doesn't. Here's how I modified it:
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXBUF 10000
int main(int argc, char *argv[])
{
FILE *fp;
char buffer[MAXBUF];
int i = 0, ch;
if(argc < 2) {
fp = fopen(argv[1],"r");
if(fp != NULL ) {
while((ch=fgetc(fp))!=EOF && i < MAXBUF) {
if(ch!=' ') {
buffer[i]=(char)ch;
i++;
}
}
fclose(fp);
}
else
fprintf(stderr, "\nUnable to Open Input File. Make sure it exists");
}
else
fprintf(stderr, "\nFile Not Specified.\nUsage <programname> <filename>");
return 0;
}
-Prelude