Функция для считывания данных из файла с расширением txt
Имеются две функции. Одна записывает данные в файл другая считывает. При записи всё отрабатывает хорошо. При считывании происходит ошибка доступа. Подскажите в чём ошибка.
void Func_zap(CARD_INDEX*k)
{
FILE* f;
fopen_s(&f,"my.txt", "w+");
if (f)
{
for (int i = 0; i < count; i++)
{
fprintf_s(f,"Автор:%s\nНазвание:%-15s\nГод издания:%-15d\nСтоимость:%-15.2f\nКатегория:%-15s\n",pB[i]->author, pB[i]->name, pB[i]->year, pB[i]->price, pB[i]->strCategory[pB[i]->category]);
}
}
else
{
std::cout << "Не удалось открыть файл";
}
fclose(f);
}
void Func_fail(CARD_INDEX* k) {
FILE* f;
fopen_s(&f, "my.txt", "r");
if (f)
{
pB[count] = new BOOK;
fscanf_s(f, "Автор:%s\nНазвание:%s\nГод издания:%d\nСтоимость:%.2f\nКатегория:%d\n", pB[count]->author,pB[count]->name, &pB[count]->year, &pB[count]->price, &pB[count]->strCategory[pB[count]->category]);
count++;
quantity++;
//printf_book(pB[count]);
}
else
{
std::cout << "Не удалось открыть файл";
}
fclose(f);
}
Ответы (1 шт):
Автор решения: Eugene X
→ Ссылка
Очередная жесть.
- Зачем вы используете функции языка Cи в С++? Вы уж определитесь вы на C++ или на классическом Си пишете. Ваш код выглядит как "Крутой пацан в ферари, а с ним рядом на сидении сидит старая морщинистая бабка"
- Если используете "русские буквы", то обязательно надо использовать wstring. Это избавляет от кучи багов. Старые методы не умеют работать с long char кодировками.
- Зачем использовать пойнтеры и массивы?! Когда в плюсах есть отличная вещь как list???!
#include <iostream>
#include <list>
#include <fstream>
using namespace std;
typedef struct {
string author;
string book;
unsigned short published;
float price;
string category;
} Bookshelf;
list<Bookshelf> bookshelf;
void add(string author, string book, unsigned short published, float price, string category) {
Bookshelf item = *(new Bookshelf());
item.author = author;
item.book = book;
item.published = published;
item.price = price;
item.category = category;
bookshelf.push_back(item);
}
void freemem(void) {
bookshelf.clear();
}
int main(void) {
add("Vasilij Pupkin", "Kniga", 1990, 20, "Hlam");
add("Tester", "testie", 1991, 10.5, "Hlam");
// write out
ofstream out("output.txt");
for (auto book: bookshelf) {
out << book.author << endl << book.book << endl
<< book.published << endl << book.price << endl
<< book.category << endl;
}
freemem();
out.flush();
out.close();
// read in
string author, book, published, price, category;
ifstream in("output.txt");
while (!in.eof()) {
if (getline(in, author) && getline(in, book) &&
getline(in, published) && getline(in, price) &&
getline(in, category))
{
add(author, book, stoi(published), stof(price), category);
}
}
in.close();
// list
for (auto book: bookshelf) {
cout << "Author: " << book.author << endl
<< "Book: " << book.book << endl
<< "Published: " << book.published << endl
<< "Price: " << book.price << endl
<< "Category: " << book.category << endl << endl;
}
freemem();
return 0;
}
Вывод.
root@__server__:/__path__/writefile# ./writer
Author: Vasilij Pupkin
Book: Kniga
Published: 1990
Price: 20
Category: Hlam
Author: Tester
Book: testie
Published: 1991
Price: 10.5
Category: Hlam
root@__server__:/__path__/writefile# cat output.txt
Vasilij Pupkin
Kniga
1990
20
Hlam
Tester
testie
1991
10.5
Hlam