Answer the question
In order to leave comments, you need to log in
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
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");
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 questionAsk a Question
731 491 924 answers to any question