質問

I wrote this basic function :

int save_files(PCHAR fileName)
 {
     errno_t         err;
     FILE*           pFile    =    NULL;

do
{
    if (!fileName)
    {
        printf("Input is NULL \n");
        break;
    }


    err = fopen_s( &pFile, fileName, "r");
    if(0 != err)
    {
        printf("The file %s was not opened for reading\n", fileName);
    }
    else
    {
       printf("The file %s was opened for reading \n", fileName);
    }

    /*getting the fileSize */
    fileSize    =   dbg_getFileSize(pFile);
    printf("############# FILE SIZE IS :  %d #############\n" );
 }

this is the function get file size :

UINT32 dbg_getFileSize(FILE *file)
 {
        UINT32  size = 0 ;

         if (file == NULL)
            {

            return -1;
             }

         fseek(file , 0L , SEEK_END);
         size = ftell(file);
         fseek(file, 0L, SEEK_SET);/*set it to the head!!! */

         return size;

     }

I open the same path all the time , and get different size every time I tried opening it with "r" and "rb" , but still getting the same different numbers..

役に立ちましたか?

解決

You get different file sizes because the following line:

printf("############# FILE SIZE IS :  %d #############\n" );

doesn't actually specify the variable you're trying to print. Hence it's probably getting whatever rubbish is on the stack when you call it (I say probably, but anything could happen given that you've invoked the dreaded "undefined behaviour" (a)).

You might want to try this instead:

printf("############# FILE SIZE IS :  %d #############\n", fileSize );

(a) From C99 7.19.6.1 The fprintf function, unchanged in C11 7.20.6.1, the equivalent section:

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.

他のヒント

You forgot to add fileSize to your printf, instead you're printing random information from your stack or registers.

As paxdiablo pointed out, you are not using variable name. So as a result, printf would take a value which is on the stack and try to print it - this is an undefined behavior.


Undefined behavior The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored.
See http://cims.nyu.edu/cgi-systems/man.cgi?section=3C&topic=printf

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top