-3

I have a problem when I close the file fc. Here is my code

#include <stdio.h>
#include <wchar.h>
int main()
{
   FILE* fc = fopen("template.txt","rt,ccs=UTF-8");
   wchar_t subStr[2300];  
   fread(subStr,sizeof(wchar_t),2300,fc);
   wchar_t* scrStr=new wchar_t[2300];
   wcscpy(scrStr,subStr);
   fclose(fc);
   return 0;
}
6
  • 3
    ... what problem do you have? May 15, 2015 at 15:33
  • 3
    (1). This is not valid C code. (2). How do you know you can't close the file? have a problem is unclear.
    – Yu Hao
    May 15, 2015 at 15:34
  • 4
    Check the return value of fopen(). It returns null if the file could not be opened. May 15, 2015 at 15:34
  • 1
    Also why are you using wchar_t for UTF-8 (an 8-bit format)? May 15, 2015 at 15:34
  • 1
    maybe buffer overrun at wcscpy
    – BLUEPIXY
    May 15, 2015 at 16:04

1 Answer 1

0

The file was probably not opened correctly in the first place. You must check that the 'handle' to the stream returned by fopen is not NULL. The following code checks the file 'handle', with a few bits changed to make it 'reasonable' C.

#include <stdio.h>
#include <wchar.h>
int main()
{
    wchar_t* scrStr = NULL;  
    FILE* fc = fopen("template.txt","rt,ccs=UNICODE");
    // Check that the file was opened.
    if(NULL != fc)
    {
        wchar_t subStr[2301];  
        size_t wcharsRead = fread(subStr, sizeof wchar_t , 2300, fc);
        fclose(fc);
        // Check if anything was read.
        if(0 != wcharsRead)
        {
            // Terminate the string in the temporary buffer.
            subStr[wcharsRead] = `\0`;
            // Allocate a smaller string (use new, if you're in C++).
            if(scrStr = malloc(1 + sizeof wchar_t * wcharsRead), NULL != scrStr)
            {
                // Copy the useful bit into the new string.
                wcscpy(scrStr, subStr);
            }
        }
    }
    else
    {
        // Do some error handling
        printf("Unable to open file.  Error code: %d\r\n",errno);
    }
    // Check if a string was read.
    if(NULL != scrStr)
    {
         // Do something with scrStr
         // Free the string once it's finished with (use delete if you're in C++).
         free(scrStr);
    }
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.