簡體   English   中英

嘗試使用分配的 memory 中的 fwrite() 填充文件

[英]Trying to fill file with fwrite() from allocated memory

在我的項目中,我有這個結構,里面有一些東西。 我被要求分配 memory,給它值並將這些值存儲在 memory 中。 然后(我知道這很奇怪)我被要求將 memory 中的值移動到文件中。

這是正在發生的事情的要點:

文件1.h

typedef struct s1{
   int a;
   double b;
   char c;
} THING;

文件2.c

#include <stdlib.h>
#include <stdio.h>
#include "File1.h"     // Note File1.h must be in the same directory as File2.c

int main(void)
{
   THING *ptr = malloc(sizeof(THING));
   if(ptr == NULL)
   {
       fprintf(stderr,"Memory could not be allocated!");
       return 1;
   }

   ptr->a = 10;
   ptr->b = 25.4;
   ptr->c = 'A';

   /*code goes here to move from memory to file*/

   return 0;   
}

我在想我使用這樣的東西:

fwrite(&ptr, sizeof(ptr), 1, filename);

但由於某種原因,這不起作用。 什么都寫不出來。

另外,為了檢查它是否有效,我會這樣寫(我猜):

if( (fwrite(&ptr, sizeof(ptr), 1, filename)) != 1 )
{
    printf("Thing not copied to file!");
}

文件是字節流。 要將數據寫入文件,您必須創建一個 stream 字節,以某種可理解的格式保存文件中的數據。 不能保證您的THING結構具有任何特定的表示形式,因此不能保證您能夠從文件中讀回它並理解它。

如果您將sizeof(ptr)更改為sizeof(*ptr) ,您的代碼將起作用。 但這只能靠運氣。 您應該學習如何以某種定義的格式將數據從本機數據序列化為 stream 字節。

暫無
暫無

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

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