简体   繁体   中英

fprintf isn't writing to file

I am trying to use the following C code to print out an array that I have passed in. It should output the text in hexadecimal format one on each line and I have no problems opening the file. When I first wrote it, I had no problems with it working I opened the output file and my array was there. I changed the fileOutName parameter and now I can't get it to print out anything I have tried changing it back and to a few other things and nothing seems to work. Also when I debug it seems like pOutfile is a bad pointer, but like I said it still creates the file it just won't write anything in it. Any help would be appreciated. Thanks

printoutput(int output[], char * fileOutName){
    int i = 0;
    FILE * pOutfile;
    pOutfile = fopen( fileOutName, "w" );
    while(output[i] != 0){
        fprintf( pOutfile, "0x%0.4X\n", output[i] );
        i++;
    }
}

Always clean up after yourself. You're missing an fclose(pOutfile) .

It should output the text in hexadecimal format one on each line ...

This line

fprintf( pOutfile, "0x%0.4X\n", 5 );

always formats the same number - 5 . It probably should be

fprintf( pOutfile, "0x%0.4X\n", output[i] );

You're counting on the element beyond the bounds of the array to be 0, which may not be the case unless you're explicitly setting it. If you are, that's okay. Usually, pass arrays along with their size; this is safer, easier to read, and more portable.

printoutput(int output[], int size, char * fileOutName){
    int i=0;
    FILE * pOutfile;
    pOutfile = fopen( fileOutName, "w" );
    while(i!=size){
        fprintf( pOutfile, "0x%0.4X\n", output[i] );
        ++i;
        }
    fclose(pOutfile)
}

Also, I HIGHLY recommend getting used to using the pre-increment operator instead of post-increment. In situations like this, it probably won't make a difference, but for large inputs or complex types, it can reduce execution time. Hence, ++i instead of i++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM