简体   繁体   中英

Reading file with visual c++ form behaves differently than reading in C program

I'm build a graphical program using visual c++ form. I'm trying to read a file to a string. The contents of the file is simple html code.

Now, if i create a blank project and create a .c file with this code:

FILE *f;
int tamanho;
char *asd;

f=fopen("mail.txt","r");
if(f==NULL)
    erro("Erro abrir file");

fseek(f,0,SEEK_END);
tamanho=ftell(f);
rewind(f);
asd=(char *)malloc(tamanho+1);
fread(asd,1,tamanho,f);

It copies the whole to the string.

However if I create a windows form application and write the same code it only copies a few lines of my file.

fread() does not guarantee to read everything you ask for.

You need to check the return value to see how much was actually read.
You may need to do this in a loop until you have read everything you want.

size_t  read = 0;
while(read != tamanho)
{
    size_t amount = fread(asd + read,1,tamanho - read,f);

    if (amount == 0)
    {    // You may want to check for read errors here
    }

    read += amount;
}

Missing a while loop? That way u make sure u reach end of file properly

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