0

テキストファイルに書き込むプログラムがあります。

私のテキストファイルの例:

4
QA131 100 100 100 100
QA132 100 100 100 100
QA133 100 100 100 100
QA134 100 100 100 100

レコードを保存する新しい行を書きたいのですが、4 が 5 に変わります。

ファイルへの書き込みに使用される方法は何ですか?

これが私のコードです:

void inputRecord()
{
    Product product[101];
    char FILENAME[20];

  cout<<"Enter the file you want to open: ";
  cin>>FILENAME;
  ifstream read(FILENAME);
  if (read.is_open())
  {
      while(read.good())
      {
          read>>product[0].line;
            for(int i =0;i< product[0].line;i++)
            {
                read >>product[i].PartNumber 
                     >>product[i].initialQuantity
                     >>product[i].quantitySold 
                     >>product[i].minQuantity
                     >>product[i].price;
            }
             product[0].line+=1;
      }
      read.close();
  }




    ofstream write(FILENAME);
    write<<product[0].line << endl;
             for(int i =0;i< product[0].line;i++)
                {
                    write << product[i].PartNumber << '\t'
                          << product[i].initialQuantity << '\t'
                          << product[i].quantitySold << '\t'
                          << product[i].minQuantity << '\t'
                          << product[i].price << '\t' << endl;
                }
    write.close();

    cout << "Inventory added successfully!" << endl;
    system("pause");
    system("CLS");

}

アイテムをファイルに書き込めません。

4

1 に答える 1

2

fseek を使用して問題を解決できます。

これは、このC++ 参照例に基づいた非常に単純な例です。

#include<cstdio>

int main(void) {
  FILE * pFile;
  pFile = fopen ( "test.txt" , "wb" );

  fprintf(pFile,"00000\n"); // watch spacing

  for (int i=1; i<11; i++) {
    fprintf (pFile, "%d. This line a line of stuff.\n",i);
  }

  fseek(pFile , 0 , SEEK_SET );
  fprintf(pFile,"10   \n"); 
  fclose(pFile);

  return 0;
}
于 2013-09-12T15:27:55.790 に答える