hello everybody!
I wanted to post this thread just to ask for your comments about this code, but unfortunately i just realized that i have also a bug in it so i have to make a double question for help and comments...
The excercise should be (is) very simple: open a file and copy it to another file with the same name followed by ".short" by leaving at most 1 empty line when more than 1 consecutive such lines are met.
Example:
[\n]
hello
[\n]
[\n]
should become the same without the last [\n].
I wanted to write a program which checked all the bad cases (thing which usually i don't do, above all while writing files.. ) and this is my program:
it seems to work but i get a very worrying "STACK SMASH DETECTED. Aborted" error....Code:#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { FILE *fPtr,*tmpPtr; char filename[]="examXX906.txt"; if ((fPtr=fopen(filename,"r"))!=NULL) { if ((tmpPtr=fopen("tmpXX906.txt","w+"))!=NULL) { int ch,isempty=1,emptylines=0; while ((ch=fgetc(fPtr))!=EOF) { if (ch!='\n') { emptylines=0; isempty=0; if (fputc(ch,tmpPtr)==EOF) { printf("ERROR WRITING THE TEMP FILE\n"); exit(1); } } else { if ((isempty==1)) { emptylines++; if (emptylines<2) { if (fputc(ch,tmpPtr)==EOF) { printf("ERROR WRITING THE TEMP FILE\n"); exit(1); } } } else { isempty=1; if (fputc(ch,tmpPtr)==EOF) { printf("ERROR WRITING THE TEMP FILE\n"); exit(1); } } } } if (ferror(fPtr)) { printf("ERROR WHILE READING SOURCE FILE\n"); exit(1); } else { FILE *targetPtr; strcat(filename,".short"); if ((targetPtr=fopen(filename,"w+"))!=NULL) { rewind(tmpPtr); while ((ch=fgetc(tmpPtr))!=EOF) { if (fputc(ch, targetPtr)==EOF) { printf("ERROR WRITING THE TARGET FILE\n"); exit(1); } } if (ferror(tmpPtr)) { printf("ERROR WHILE READING TEMP FILE\n"); exit(1); } fclose(fPtr); fclose(targetPtr); fclose(tmpPtr); remove("tmpXX906.txt"); } else { fclose(fPtr); fclose (tmpPtr); remove("tmpXX906.txt"); printf("Couldn't create target file\n"); exit(1); } } } else { fclose(fPtr); printf("Couldn't open temp file\n"); exit(1); } } else { printf("Couldn't open source file\n"); exit(1); } return 0; }
what is wrong there?
and above all, since on saturday i will be asked to write a (maybe) similar program on a sheet of paper, i'd kindly like to ask you hints for writing programs that deal with file by minimizing the possibilities of mistakes (if you forget a ";" you don't pass this exam...)..
For example, i thought to solve this same excercise by using FGETS() but i think that it's better to have a small set of functions which have not a wide variety of worst-cases while writing on paper, do you agree?
many thanks for all your help/hints!
Bye



LinkBack URL
About LinkBacks





i really hoped it was not a conceptual mistake!