I
I
igoodmood2016-05-27 20:01:35
C++ / C#
igoodmood, 2016-05-27 20:01:35

Is it possible to work with two binary files at the same time in C++?

Is it possible to work with two binary files at the same time in C++? For example, there is a binary file, it contains numbers in random order: negative and positive. Can the program simultaneously open an existing file with given numbers and a new one, into which the numbers will be written in the required order?
For clarity, I want to show a code fragment so that the essence is clear (the code is not yet working,):

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
  setlocale (LC_ALL, "RUS");
  int n, i;
  double *a;
  FILE *f,*z; 
  f=fopen("D:\\steam\\noobs.dat", "rb");
  fread(&n, sizeof(int), 1, f);
  a=new double[n];
  fread(a, sizeof(double), n, f);
  z=fopen("D:\\steam\\noobs.dat", "wb");
  fwrite(&n, sizeof(int), 1, z);
  for(int i = 1; i<=n; i++)
  {
    if(a[i]<0)
    {
      cin >> a[i];
      fwrite(&a, sizeof(double), 1, z);
    }
  }
  fclose(z);
  fclose(f);
  system("pause");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
#
#algooptimize #bottize, 2016-05-27
@user004

Yes

M
Makaleks, 2016-05-27
@Makaleks

  1. Yes C++ can work with 2 binaries. Once again - files , not one file, open for reading and writing at the same time! How, in your opinion, to read from a file or write to it, if it is already opened before for writing? I'll try an analogy: how can tourists take pictures of one picture in a glass stand if the author took it away to finish a couple of strokes? You can read from everywhere at the same time, but you cannot do something with a file opened for writing.
    In your case, before opening for writing, you can call fclose(f) , since you saved everything you wanted.
    Read "C++ Complete Reference" (G.Schildt) - many questions will quickly disappear (there are examples there).
    int N1 = 0;
      double *array;
      FILE *file; 
      file=fopen("D:\\steam\\noobs.dat", "rb");
      fread(&N1, sizeof(int), 1, file);
      array=new double[N1];
      fread(array, sizeof(double), N1, file);
      fclose(file);
      file=fopen("D:\\steam\\noobs.dat", "wb");
      int N2 = 0;
      fwrite(&N2, sizeof(int), 1, file); // резервируем в начале файла место под N2
      for(int i = 0;  i < N1; i++)
      {
        if(array[i]<0)
        {
          printf("%lg, " array[i]);
          fwrite(&array, sizeof(double), 1, file);
          N2++;// N2 != N1 !!!
        }
      }
      fseek(file, 0, SEEK_SET);// в начало
      fwrite(&N2, sizeof(int), 1, file);// N2 != N1 !!!
      fclose(file);
      system("pause");

D
Daniil Demidko, 2016-06-06
@Daniro_San

No need to use C-libs mixed with STL.
I'm talking about fopen and cin /cout .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question