开发者

fwrite, fread - problems with fread

I have following code:

int main()
{
    char* pedal[20];
    char* pedal2[20];
    for (int i = 0; i < 20; i++)
    {
        pedal[i] = "Pedal";
    }
    FILE* plik;
    plik = fopen("teraz.txt","wb");
    for (int i = 0; i < 20; i++)
    {
       fwrite(pedal[i],strlen(pedal[i]),1,plik);
    }
    system("pause");
    fclose(plik);
    plik = fopen("teraz.txt","rb");
    for (int i = 0; i < 20; i++)
    {
        fread(pedal2[i],5,1,plik); //I know for now that every element has 5 bytes
   开发者_JAVA技巧 }
    for (int i = 0; i < 20; i++)
    {
        std::cout << pedal2[i] << std::endl;
    }
    fclose(plik);
    system("pause");
    return 0;
}

It's crashing at reading and second question let's assume that I have structure where I keep like integers, floats and also char* array and how can I easly write whole structure to the file? Normal fwrite with sizeof structure is not working


Your problem that you didn't allocate buffer for reading. In fact line

fread(pedal2[i],5,1,plik)

reads to unknown place. You need allocate memory (in your case it is 5 + 1 bytes for zero terminated string).

pedal2[i] = malloc(5+1);
fread(pedal2[i],5,1,plik)

Don't forget to release it after usage.


You can't read into pedal2 without first having allocated space for it.

You need something like this:

for (int i = 0; i < 20; ++i) {
    pedal[i] = malloc(100); //allocate some space
}


Your first question seem to have already been answered by Simone & Dewfy.

For your second question about how to write structure values into the file, you will have to write member by member.

Please check fprintf. You can probably use it for writing different data types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜