A couple of questions really about the code below from which I gained assistance in a previous post.
1). Any ideas why at the end of the ouput, I get a random garbage character printed? I am freeing the files etc and checking for EOF.
2). The idea is that it can work with multiple file arguements, so I want to create new file names which increment, i.e. out[i].txt, is that possible in C?
The code itself takes a file containing words all separated by spaces, like a book for example, then loops through, and replaces each space with a \n so that it forms a list, please find the code below:
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
/*
*
*/
int main(int argc, char** argv) {
FILE *fpIn, *fpOut;
int i;
char c;
while(argc--) {
for(i = 1; i <= argc; i++) {
fpIn = fopen(argv[i], "rb");
fpOut= fopen("tmp.out", "wb");
while (c != EOF) {
c = fgetc(fpIn);
if (isspace(c))
c = '\n';
fputc(c, fpOut );
}
}
}
fclose(fpIn);
fclose(fpOut);
return 0;
}
When you reach the end of file, you don’t
breakthe loop. So you are callingfputc(c, fpOut);withc==EOFwhich is probably an undefined behavior, or at least the writing of a\0xffbyte.And you don’t call
fcloseinside yourwhile(argc--)loop, so your files (except the last) are mostly never closed nor flushed.At last, you don’t test the result of
fopenand you should test that it is non null (and print an error message, perhaps with something aboutstrerror(errno)orperror, in that case).You should have found out with a debugger (like
gdbon Linux), and perhaps with the help of compiler warnings (butgcc-4.6 -Walldid not caught any bugs on your example).You could decide that the output file name is related to input file name, perhaps with