简体   繁体   English

以可视c ++格式读取文件的行为与在C程序中读取行为不同

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

I'm build a graphical program using visual c++ form. 我正在使用可视c ++格式构建图形程序。 I'm trying to read a file to a string. 我正在尝试将文件读取为字符串。 The contents of the file is simple html code. 该文件的内容是简单的html代码。

Now, if i create a blank project and create a .c file with this code: 现在,如果我创建一个空白项目并使用以下代码创建一个.c文件:

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. 但是,如果我创建Windows窗体应用程序并编写相同的代码,则它只会复制文件的几行。

fread() does not guarantee to read everything you ask for. fread()不能保证读取您要求的所有内容。

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 这样,您可以确保正确到达文件末尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM