K
K
Klindeu2017-05-13 14:26:05
C++ / C#
Klindeu, 2017-05-13 14:26:05

How to write a structure to a file in C++?

It is necessary to create an application that would write the structure to a file and display it on the screen.
Tried to implement it.
But unfortunately does not write the entire structure to the file. Or writes incorrectly.
Here is the code that I tried to implement:

#include "stdafx.h"
#include "string.h"
#include "stdio.h"
#include <iostream>
#include <fstream>
using namespace std;





void inputf(ifstream &f, char a[300], char b[300], char c[300], char d[300]);
void outputf1(ofstream &f, char a[300], char b[300], char c[300], char s[40]);
void main() // Основная функция
{
  int c;
  setlocale(LC_ALL, "Russian");
  cout << "Вывести на экран-1\nЗаписать в файл-2" << endl;
  cin >> c;
  if (c == 2)
  {
    int const N = 3;
    int i,j=0;
    struct vvod {
      char fam[300];
      char id[300];
      char number[300];
    };
    vvod v[N];
    for (i = 0; i < N; i++)
    {
      cout << "Введите фaмилию(Eng):" << endl; cin >> v[i].fam;
      cout << "Введите ID:" << endl; cin >> v[i].id;
      cout << "Введите номер:" << endl; cin >> v[i].number;
    }
    
    ofstream f1;
    for (i = 0; i < N; i++)
    {
      
      outputf1(f1, v[i].fam, v[i].id, v[i].number, "writer.txt");
      
    }
    
  }
  else if (c == 1)
  {
    char str[40];//Строковая переменная (для пути к файлу)
    cout << "\n Введите имя файла \n";
    cin >> str;
    char v[900];
    char q[300];
    char w[300];
    char e[300];
    ifstream f;
    inputf(f,str,q,w,e);

  }
}

void outputf1(ofstream &f, char a[300], char b[300], char c[300], char s[40])//Функция для записи
                         
{
  f.open(s);//Открываем файл
        //Проверка успешности открытия файла:
  if (f.fail()) {
    cout << "\n Ошибка открытия файла";
    exit(1);
  }
  f << a;//записываем переменную в файл
  f << b;
  f << c;
  f.close();//Закрываем файл
}

void inputf(ifstream &f, char a[300],char b[300], char c[300],char d[300] )//Функция для чтения 
{
  f.open(a);//Открываем файл
  //Проверка успешности открытия файла:
  if (f.fail()) {
    cout << "\n Ошибка открытия файла";
    exit(1);
  }
  f >> b;//Читаем переменную из файла
  f >> c;
  f >> d;
  cout << b << endl;
  cout << c << endl;
  cout << d << endl;
  f.close();//Закрываем файл
}

Tell me where you screwed up.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2017-05-13
@none7

The >> and << operators are very capricious. And they recognize char[300] as char*. A buffer overflow may occur if there are more than 300 characters, and reading or writing will be stopped if a space, end-of-line, or \0 character is encountered. Accordingly, when writing, not 300 bytes are written, but before the separator. When reading, no delimiters will be encountered so that everything will be read into the first structure and a buffer overflow may occur. Use istream::getline(void), istream::read(char* buf, streamsize n), ostream::write(const char* buf, streamsize n);
In general, it is better not to mix C and C ++, certain bugs will pop up everywhere. Instead of char[300] std::string, instead of std::array or std::vector arrays. It is also desirable to get rid of a fixed length and serialize the data, say, in .csv

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question