user1091446
user1091446

Reputation: 61

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.

Upvotes: 0

Views: 623

Answers (2)

Loki Astari
Loki Astari

Reputation: 264581

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;
}

Upvotes: 3

sys_debug
sys_debug

Reputation: 4003

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

Upvotes: 1

Related Questions