none
file read failure

    Question

  • I made a new Win32 console project with the following code. The program exits with exit code 5. It fails to read from the file just before fclose. I am facing the problem in another code.  Here i have recreated the problem. Any idea what i could be doing wrong??

    #include "stdafx.h"

    int _tmain(int argc, _TCHAR* argv[])
    {
        FILE *fp;
        unsigned char data[4];
        if((fp = fopen("testdump","wb+"))==NULL)
            exit(1);
        if(fwrite("text",sizeof(char)*4,1,fp)==0)
            exit(2);
        fclose(fp);

        if((fp = fopen("testdump","wb+"))==NULL)
            exit(3);
        if(fseek(fp, 0, SEEK_SET)!=0)
            exit(4);
        if(fread(&data[0],sizeof(char)*4,1,fp)==0)
            exit(5);
        fclose(fp);

        return 0;
    }

    Thursday, October 04, 2007 1:17 PM

Answers

  • I realized my mistake.. i was using mode wb+ which truncates the file to zero length before opening. Hence the read call would read zero bytes..
    Thursday, October 04, 2007 1:34 PM

All replies

  • I dont know why above shoudl fail, but I want to recommand a correct use of fread and fwrite,

     

    You need to supply size of single element in second argument (which in your case of sizeof(char)) and count = number of items (4 items in your case). I have seen problem with reading becase of this type of misuse. I guess fread/fwrite simply does not multiply the count*size to read bytes.

    Thursday, October 04, 2007 1:26 PM
  • I realized my mistake.. i was using mode wb+ which truncates the file to zero length before opening. Hence the read call would read zero bytes..
    Thursday, October 04, 2007 1:34 PM