![](/img/trans.png)
[英]C++ how to write header file prototype for a function that accepts an array of object pointers.
[英]How to write pointers of an object into a file?
我遇到一種情況,需要將對象的指針存儲到文件中,然后在同一過程中再次讀取它。 我該怎么辦?
現在,我這樣寫/讀:
Myclass* class = <valid pointer to Myclass>
FILE* output_file = fopen(filename, "w");
fwrite(class, sizeof(class), 1, output_file)
// and read it
FILE* in_file = fopen(filename, "r");
Myclass* class_read
fread(class_read, sizeof(class_read), 1, in_file)
回讀時看不到正確的值。 我將在相同的地址空間中讀取和寫入這些文件。
要讀寫指針本身,您需要傳遞其地址,而不是其指向的地址:
fwrite(&class, sizeof(class), 1, output_file);
fread (&class_read, sizeof(class_read), 1, in_file);
^
相反,您正在寫任何class
指向的前幾個字節,然后嘗試將它們讀回任何class_read
指向(如果它不是有效的指針,則失敗)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.