簡體   English   中英

如果可以,我可以從文件中檢索結構嗎?

[英]Can I retrieve a struct from a file if so how?

所以,我有這個結構數組和一個文件,我需要將所有信息復制到結構中,我可以做這樣的事情嗎? 如果不是,我怎么能做到這一點?

#include <stdio.h>
#include <iostream>

using namespace std;

typedef struct{
      int x;
      int y;
      int z;
}coordinates;

int main(){
     coordinates coordinate[100];
     int i = 0;
     FILE *f;
     f = fopen("file.file","rb");

     if(!f){
        cout << "Error";
        return 0;
     }

     while(!feof(f)){
        fread(coordinate[i],sizeof(coordinates),1,f);
        i++;
     }
     return 0;
}

好吧,如果您使用的是 C++(順便說一下,這是一種與 C 完全不同的語言)。 您只需為該類定義輸入運算符。

struct coordinates{
      int x;
      int y;
      int z;

      // Personally I prefer serialization to a straight binary format.
      // It is easy to read and validate by a human
      // and not as brittle as a binary format when anything non
      // trivial happens.
      friend std::istream& operator>>(std::istream& str, coordinates& c)
      {
           return str >> c.x >> c.y >> c.z;
      }
      friend std::ostream& operator<<(std::ostream& str, coordinates const& c)
      {
           return str << c.x << " " << c.y << " " << c.z << " ";
      }
};

現在您可以簡單地從文件中讀取結構:

int main()
{
    std::ifstream data("file.file");

    coordinates  value;
    while(data >> value) {
       std::cout << "I have a set of cordinates\n";
    }

    // To read them into an array (a vector is a resizable array available in C++)
    std::vector<coordinates>   vec;
    std::copy(std::istream_iterator<coordinates>(file),
              std::istream_iterator<coordinates>(),
              std::back_inserter(vec));
}

如何將結構寫入和讀取到二進制文件

    typedef struct{
      int x;
      int y;
      int z;
}coordinates;

寫入文件

 FILE *f;
 f = fopen("test.dat","wb");

 for(int i = 0; i < 3; i++)
 {
    coordinates c;
    c.x = 0;
    c.y = 1;
    c.z= 2;
    fwrite(&c,sizeof(coordinates),1,f);
 }

讀回結構

 FILE *f;
 f = fopen("test.dat","rb");

 if(!f){
    cout << "Error";
    return 0;
 }

 coordinates c;
 while(fread(&c,sizeof(coordinates),1,f))
 {
    cout << c.x << " " << c.y << " "<< c.z << endl;
 }

如果可以,我可以從文件中檢索結構嗎?

是的你可以。 你可以這樣做,通過readwrite方法。 打開文件並以二進制模式寫入結構。 然后,您可以使用 read 方法以二進制模式從文件中讀取。

您可以使用 write 方法以二進制方式將結構直接寫入文件:

#include <iostream>
#include <fstream>
using namespace std;

struct Player {
    int age;
    int score;
};

int main()
{
    // You can write a structure directly into a file.
    // Create an instance of 'Player':
    Player rec;
    rec.age = 10;
    rec.score = 900;

    // Create out file
    fstream out_file("rec.bin",
                     ios::trunc | ios::binary | ios::in | ios::out
                     );

    // write the whole structure into the file
    out_file.write(reinterpret_cast<char*>( &rec ),
                   sizeof( rec )
                   );
}

我們在 write 和 read 方法中將類型轉換為char* ,因為 write 方法按順序一個一個地寫入每個字符、每個字節。 因此,我們轉換為char*以直接引用這組字節。


並使用 read 方法讀取文件。
下面是讀取我們剛剛寫入文件rec.binstruct的示例:

#include <iostream>
#include <fstream>
using namespace std;

struct Player {
    int age;
    int score;
};

int main()
{
    fstream in_file("rec.bin", ios::binary | ios::in | ios::out);

    Player in_rec;

    // read in age
    if ( !in_file.read(
          reinterpret_cast<char*>( &in_rec.age ),
          sizeof( in_rec.age )
    ))
    {
        // handle error
    }

    // read in score
    if ( !in_file.read(
          reinterpret_cast<char*>( &in_rec.score ),
          sizeof( in_rec.score )
    ))
    {
        // handle error
    }

    cout << in_rec.age << endl;
    cout << in_rec.score << endl;
}

輸出:

10
900

在cord.txt 文件中使用分隔符,這樣可以很容易地檢索坐標。 如果你有這種格式的文本文件,我的代碼會很好用

cord.txt
4,5,6,
3,4,5,
7,8,9,   

根據上述文本文件格式的代碼是

typedef struct 
{
 int x;
 int y;
 int z;
}cord;

int main(int argc, char *argv[])
{
  cord cr[100];
  int i,j,k,l;
  j=0;k=0;l=0;
  char numbr[80];char numx[3];char numy[3];char numz[3];
  FILE *p;
  p = fopen("cord.txt","r");
  if(!p) { cout<<"File is missing\n"; }
  while(!feof(p))
  {
    for(i=0;i<80;i++)
    numbr[i]=NULL;
    for(i=0;i<3;i++)
    {
      numx[i]=NULL;
      numy[i]=NULL;
      numz[i]=NULL;
    }

   fgets(numbr,80,p);
   for(i=0;i<strlen(numbr);i++)
   {
      if(numbr[i]!=',')
      {
          if(k==0) {numx[l]=numbr[i];}
          else if(k==1) {numy[l]=numbr[i];}
          else if(k==2) {numz[l]=numbr[i];}
          l=l+1;    
      }
      else
      {
          l=0;
          if(k==0)
          {cr[j].x=atoi(numx);k=k+1;}
          else if(k==1)
          {cr[j].y=atoi(numy);k=k+1;}
          else if(k==2)
          {cr[j].z=atoi(numz);k=0;break;}
      }
   } 
   j=j+1;    
}
fclose(p);

for(i=0;i<j;i++)
 {   
   cout<<cr[i].x<<" "<<cr[i].y<<" "<<cr[i].z<<endl;
 }
cout<<"\n";
return EXIT_SUCCESS;
}

輸出將是 4,5,6, 3,4,5, 7,8,9

將結構寫入 FILE(或更一般地,流)的過程稱為序列化 你可以用二進制(這很困難)或文本來完成。 以下代碼對類似的數據結構執行文本序列化。

int read_coords (FILE * f, coord_t * result);
void write_coords (FILE * f, coord_t const * write_me);

/**
 * Reads a coordinate in the form x,y,z from f into result.
 * Returns non-zero on success
 */
int read_coords (FILE * f, coord_t * result)
{
  // Leading spaces in scanf cause us to elegantly handle weird whitespace
  int read = fscanf (f, " %d , %d , %d", &result->x, &result->y, &result->z);

  return read == 3;
}

void write_coords (FILE * f, coord_t const * result)
{
  fprintf (f, "%d, %d, %d\n", result->x, result->y, result->z);
}

int main (void)
{
  coord_t coord;

  printf ("Gimme Coords: ");
  if (read_coords (stdin, &coord))
  {
    printf ("I got: ");
    write_coords(stdout, &coord);
  }
  else
  {
    printf ("I had an error reading those coords.");
  }

  return 0;
}

PS,看起來你在上C班。 我建議暫時避免。 您可以在同一個程序中混合和匹配不同的 I/O 方法,但這會使事情變得混亂。

暫無
暫無

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

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