簡體   English   中英

如何正確使用fread()讀取指定長度的內容(C語言)

[英]How to correctly use fread() to read in specified length of content (C language)

我使用fwrite()函數將4個數據塊寫入一個名為“ example2.bin”的文件中。 在文件的開頭,我還寫了塊數(在此追逐中為4)。 每個塊包含以下格式的數據:0(偏移),4(字符串的大小)和字符串“ dang”。

我首先將內存地址復制到char * buffer,其中包含塊數和4個數據塊,如上所述。 然后,我執行以下操作:

filePtr = fopen("example2.bin", "wb+");
fwrite(buffer, contentSize, 1, filePtr); /*contentSize is the sum of the 4 blocks in byte */

fwrite()運作良好,我能夠看到保存在文件example2.bin中的字符串。 但是,我在解析文件example2.bin時遇到問題:

int main()
{

    FILE *filePtr;
    int listLength = 0;
    int num_elements = 0;
    int position = 0;
    int offset = 0;
    int size = 0;
    char *data;

    listLength = fileSize("example2.bin");  /* get the file size in byte */
    filePtr = fopen("example2.bin", "rb");

    fread(&num_elements, 1, 1, filePtr);   /* get the number of blocks saved in this file */
    printf("num_elements value is %d \n", num_elements);
    position += sizeof(num_elements);     /* track the position where the fread() is at */
    printf("before the for-loop, position is %d \n", position);

    int index;
    for (index = 0; index < num_elements; index++)
    {
        fread(&offset, position, 1, filePtr);
        position += sizeof(offset);
        printf("offset is %d and position is %d \n", offset, position);

        fread(&size, position, 1, filePtr);
        position += sizeof(size);
        printf("size is %d and position is %d \n", size, position);

        fread(data, position, 1, filePtr);
        position += size;
        printf("size is %d and data is %s \n", size, data);
    }
    return 0;
}

運行編譯的程序時,得到以下輸出,這對我來說很奇怪:

num_elements的值是4
在for循環之前,位置為4
偏移量為0,位置為8
大小為67108864,位置為1996488708分段錯誤(核心已轉儲)

我不明白為什么人數和職位增加到如此之大。 我感謝您的幫助。

我想我已經找出分段錯誤錯誤的原因:我沒有為指針data分配內存

執行malloc后,分段錯誤錯誤消失了: data = malloc(size); 在此行之前fread(data, size, 1, filePtr);

在for循環的最后,我還需要通過以下方式free(data);分配的內存: free(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM