簡體   English   中英

以多平台方式將4個數組寫入文件的最簡單方法是什么?

[英]What is the simplest way to write 4 arrays into a file in a multiplatform way?

假設我們有一個int數組,float數組等結構,我們需要將它們寫入二進制格式文件以進行快速重載。 可以用簡單的方法完成嗎?

每個數組的文件應該是幾個嗎?

用純文本編寫...然后將其壓縮

快點! 二進制格式

除非您有大量數據,否則只需編寫標准文本格式即可。 如果可以假設兩端都使用c99,請對浮點數據使用%a格式化程序,以使自己與二進制十進制轉換的變數隔離。

如果數據量巨大,或者出於其他原因需要使用“原始數據”格式,則需要在寫入之前將數據轉換為已知的字節序,並在讀取后轉換回主機的字節序。 任何合理的操作系統都具有用於執行這些轉換的庫例程。

我對C有點生疏,但可能有人寫過將陣列序列化為二進制數據的支持,專門用於寫入和/或讀取文件。 Google針對您的特定語言進行了序列化,可能有人已經為您解決了此問題。

man fwrite / fread

但是,如果您使用一些奇怪的平台, 字節序可能是個問題。 另外,您可能應該在所有平台上使用固定大小的類型。

如果您只是在尋找示例,則以下是一個非常簡單的示例,其中完全沒有錯誤檢查。 它將具有一些整數的結構的內容寫入文件,然后再次讀出它們。 但是,其他人關於字節順序的觀點非常緊密,如果要在不同平台上使用該文件,則需要解決。

typedef struct {
   int count;
   int *values;
} SomeInts;


int main(int argc, char* argv[])
{
   SomeInts ints;
   int i;
   FILE *fh;

   ints.count = 5;
   ints.values = (int*)malloc( ints.count * sizeof(int));
   for ( i = 0; i < ints.count; i++ )
      ints.values[i] = i * 42;

   // write it
   fh = fopen( argv[1], "wb" );
   // really should check amount written to verify it worked
   fwrite( &ints.count, sizeof( ints.count ), 1, fh );
   fwrite( ints.values, sizeof(ints.values[0]), ints.count, fh );
   fclose(fh);

   // read them back in.
   free( ints.values );
   memset( &ints, 0, sizeof( ints ));


   fh = fopen( argv[1], "rb" );
   // read how many ints (should also check for errors)
   fread( &ints.count, sizeof( ints.count ), 1, fh );
   ints.values = (int*)malloc( ints.count * sizeof(int));
   fread( ints.values, sizeof(ints.values[0]), ints.count, fh );
   fclose(fh);

   for ( i = 0; i < ints.count; i++ )
      printf( "%d\n", ints.values[i] );

   free( ints.values );

}

如果您使用pragma pack(1),則可以在一塊內存中進行一次寫入/讀取操作。

#include <stdio.h>  
#include <memory.h>  
typedef struct ca_tag{  
int i[4];  
float f[3];  
}ca_type;  

#pragma pack(1)  
void init(ca_type* c)  // fill it with something
{  
   c->i[0] = 1; c->i[1] = 2; c->i[2] = 3; c->i[3] = 12;  
   c->f[0] = 2.3; c->f[1] = 32.3; c->f[2] = 42.3;  
}  
int main()  
{  
   FILE *stream;  
   ca_type ca;  
   char *ptr = (char*)&ca;  
   char *ptr2 = (char*)&ca;  
   init(&ca);  
   if( (stream = fopen( "test.out", "wb" )) != NULL )  
      fwrite( ptr, sizeof( ca ), 1, stream );  
   else  
      printf( "Problem opening for write\n" );  
   fclose(stream);  
   memset((void *)&ca, 0, sizeof(ca));// zero the lot  
   if( (stream = fopen( "test.out", "rb" )) != NULL )  
     fread( (void*)ptr2, sizeof( ca ), 1, stream );  
   else  
      printf( "Problem opening for read\n" );  
   return 0;  
}  

錯誤檢查需要像以前一樣

暫無
暫無

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

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