Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

c - Working with Text Files Two

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 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 = '
';
            fputc(c, fpOut );
        }
    }
}
fclose(fpIn);
fclose(fpOut);
return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you reach the end of file, you don't break the loop. So you are calling fputc(c, fpOut); with c==EOF which is probably an undefined behavior, or at least the writing of a xff byte.

And you don't call fclose inside your while(argc--) loop, so your files (except the last) are mostly never closed nor flushed.

At last, you don't test the result of fopen and you should test that it is non null (and print an error message, perhaps with something about strerror(errno) or perror, in that case).

You should have found out with a debugger (like gdb on Linux), and perhaps with the help of compiler warnings (but gcc-4.6 -Wall did not caught any bugs on your example).

You could decide that the output file name is related to input file name, perhaps with

char outname[512];
for(i = 1; i < argc; i++) {
   fpIn = fopen(argv[i], "rb");
   if (!fpIn) { perror (argv[i]); exit(1); };
   memset (outname, 0, sizeof (outname));
   snprintf (outname, sizeof(outname)-1, "%s~%d.out", argv[i], i);
   fpOut= fopen(outname, "wb");
   if (!fpOut) { perror (outname); exit(1); };
   /// etc...
   fclose(fpIn);
   fclose(fpOut);
   fpIn = fpOut = NULL;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...