c++ 阅读和写入二进制文件[已关闭]

fdx2calv  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(168)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

2天前关闭。
Improve this question

#include <iostream>
#include <fstream>
#include <cstring>



struct Data {
  char *Hold1;
  char *Hold2;
};


int main() {
  
//Variables
  int choice , loop = 0, RecAmount = 0;
  std::string DepName, output1;
  double inp2, output2;

////File Check
   std::fstream inventory;
    inventory.open("inventory.dat", std::ios::out|std::ios::in|std::ios::binary );  
    if (inventory.fail()){
      inventory.open("inventory.dat", std::ios::out|std::ios::in | std::ios::binary|           
      std::ios::trunc);
      std::cout << "Error opening file....";
        return 0; }

  while (loop < 1) {
    std::cout << "\nRead/write testing\n";
    std::cout << "1. Input Data\n";
    std::cout << "2. Read Data Output\n";
    std::cin >> choice;

////Input 2 strings
    if (choice == 1) {
      std::cout << "Testing input\n";

      struct Data test1;
      test1.Hold1 = "First test";
      test1.Hold2 = 29;

      
     
      }

    if (choice == 2) {
      std::cout << "Testing output\n";
      
      //// Add way to choose which data is read and displayed
      inventory.read ((char *)& inp2, sizeof(Data));

      

      std::cout << "Character input = " << output1 << std::endl;
    }
  }
}

我不知道如何访问或使用二进制文件。我需要:

  • 将数字和字符数组写入二进制文件(在此文件中命名为“inventory.dat”)
  • 能够查找和读回所选信息(比如我输入了3组数据,只想显示第2组)
  • 覆盖任何选定的数据(找到第二组数据并更改它)

我以前试过查找信息,但找不到任何我能理解或使用的东西,因此任何帮助都将不胜感激。

hjzp0vay

hjzp0vay1#

下面是一个使用char数组的例子。这不是很完整,但应该可以让你从正确的方向开始。如果确实需要更多的错误检查。

const int BUFFER_SIZE = 256;

// A FIXED SIZE data structure
struct data {
    char string1[BUFFER_SIZE];
    char string2[BUFFER_SIZE];
    int i1;
    double d1;
};
if (choice == 1) {
    data test;
    std::cin >> test.string1;
    std::cin >> test.string2;
    std::cin >> test.i1;
    std::cin >> test.d1;
    // Append to end of file
    inventory.seekg(0, std::ios_base::end);
    inventory.write(reinterpret_cast<const char *>(&test), sizeof(data));
}
else {
    int recordNumber;
    std::cout << "Enter record number to read: ";
    std::cin >> recordNumber;
    data test;
    // Jump to record.
    // Ex: user enters "5". To get the file pointer to point to record #5
    // seek from the beginning of the file to 4 * sizeof(a single record)
    if (inventory.seekg((recordNumber - 1) * sizeof(test))) {
        inventory.read(reinterpret_cast<char *>(&test), sizeof(test));
        std::cout << test.string1 << ','
                  << test.string2 << ','
                  << test.i1 << ','
                  << test.d1;

    }
}

相关问题