Ofstream c ошибка

In principle, if there is a write error, badbit should be set. The
error will only be set when the stream actually tries to write, however,
so because of buffering, it may be set on a later write than when the error occurs, or even after
close. And the bit is “sticky”, so once set, it will stay
set.

Given the above, the usual procedure is to just verify the status of the
output after close; when outputting to std::cout or std::cerr, after
the final flush. Something like:

std::ofstream f(...);
//  all sorts of output (usually to the `std::ostream&` in a
//  function).
f.close();
if ( ! f ) {
    //  Error handling.  Most important, do _not_ return 0 from
    //  main, but EXIT_FAILUREl.
}

When outputting to std::cout, replace the f.close() with
std::cout.flush() (and of course, if ( ! std::cout )).

AND: this is standard procedure. A program which has a return code of 0
(or EXIT_SUCCESS) when there is a write error is incorrect.

I am getting an ofstream error in C++, here is my code

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.n";
  myfile.close();
  return 0;
}

error from Dev-C++ 10

C:devpmain.cpp aggregate
`std::ofstream OutStream’ has
incomplete type and cannot be defined

Thanks in advance

Bentoy13's user avatar

Bentoy13

4,8861 gold badge19 silver badges33 bronze badges

asked Jun 29, 2009 at 8:57

0

You can try this:

#include <fstream>

int main () {
  std::ofstream myfile;

  myfile.open ("example.txt");
  myfile << "Writing this to a file.n";
  myfile.close();

  return 0;
}

answered Jun 29, 2009 at 9:26

Viet's user avatar

VietViet

17.8k33 gold badges102 silver badges134 bronze badges

0

The file streams are actually defined in <fstream>.

answered Jun 29, 2009 at 9:28

You may not be including the appropiate header file.

adding #include <fstream> at the beggining of your source file should fix the error.

answered Feb 10, 2018 at 21:51

Sebastián Mestre's user avatar

Probably, you are including the wrong header file. There is a header <iosfwd> that is used for header files that need to reference types from the STL without needing a full declaration of the type. You still are required to include the proper header <iostream> in order to use the types in question.

answered Jun 29, 2009 at 9:14

1800 INFORMATION's user avatar

1800 INFORMATION1800 INFORMATION

131k29 gold badges159 silver badges239 bronze badges

0

Include fstream header file that’s it. Because ofstream & ifstream are included in fstream.

answered Jan 2, 2021 at 7:19

Add #include <fstream>.

Code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    std::ofstream myfile;
    myfile.open("example.txt", std::ios::out);
    myfile << "Writing this to a filen";
    myfile.close();

    return 0;
}

Sid110307's user avatar

Sid110307

4672 gold badges8 silver badges20 bronze badges

answered Jul 17, 2021 at 14:24

B_Robinson95's user avatar

1

I faced the same error because I forgot to use using namespace std;
after including it, the problem was solved.

Abhishek Dutt's user avatar

answered Apr 6, 2021 at 5:10

Rohit Chitte's user avatar

1

Artemkcore

0 / 0 / 0

Регистрация: 11.09.2019

Сообщений: 4

1

05.05.2022, 21:22. Показов 1486. Ответов 9

Метки c++, ofstream (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте!
Потребовалось написать программу, в которой нужно организовать запись списка в текстовый файл. Однако ofstream не хочет ни создавать новый файл, ни писать в существующий (код ниже, приведены лишь функции, которые могут касаться проблемы). Перерыл уже полинтернета, ставил разные флаги для функции open, но результат нулевой. Помогите, пожалуйста, разобраться

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <iomanip>
#include <fstream>
#include <list>
#include <string>
#include <conio.h>
#include <windows.h>
#include <random>
 
using namespace std;
 
struct sklad
{
    string tovar;
    int count = 0;
    double cena = 0;
    int nadbavka = 0;
};
 
list<sklad> read(list<sklad> array, string p);
void print(list<sklad> array);
list<sklad> add(list<sklad> slist);
list<sklad> remove(list<sklad> slist);
void search(list<sklad> slist);
void save(list<sklad> slist);
void chooseAction(list<sklad> sl);
 
list<sklad> arr;
int e = 1;
 
int main()
{
    string path;
 
    cout
        << setw(40) << "Введите полный путь к файлу" << endl;
    cin >> path;
 
    arr = read(arr, path);
    while (e == 1)
        chooseAction(arr);
}
 
list<sklad> read(list<sklad> array, string p)
{
    string str;
    sklad temp;
    ifstream in(p);
 
    if (in.is_open())
    {
        //парсинг файла
    }
    in.close();
    return array;
}
 
void save(list<sklad> slist)
{
    ofstream out;
    string a = "D:\путь к файлу\list.txt";
    out.open(a, ios::out | ios::trunc);
 
    if (out.is_open())
    {
        for (list<sklad>::iterator iter = slist.begin(); iter != slist.end(); iter++)
        {
            cout << iter->tovar << ", " << iter->count << ", " << iter->cena << ", " << iter->nadbavka << endl;
        }
        cout << "File saved on " + a;
        out.close();
    }
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

05.05.2022, 21:22

Ответы с готовыми решениями:

Команда fopen не создает/ не открывает файл
Папки с одинаковыми правами доступа.

В одной делаю простой код:

#include &lt;stdio.h&gt;
#include…

Студия не создает и не открывает проекты
Здравствуйте, дело было так: У меня стояли VS 2012 и VS 2013 Экспрессовские, и тут черт меня дернул…

Составить программу, которая создает каталог, создает в нем файл, переименовывает этот файл и удаляет этот файл, а потом удаляет каталог
Составить программу, которая создает каталог, создает в нем файл, переименовывает этот файл и…

Visual studio не создает и не открывает проекты
Здравствуйте, вижуал студио перестал открывать и создавать проекты, программа не выдает ошибок….

9

Нарушающий

415 / 303 / 46

Регистрация: 13.04.2022

Сообщений: 1,747

05.05.2022, 21:30

2

Дает ли попытка открытия файла сообщение об ошибке?



0



24 / 57 / 31

Регистрация: 06.08.2020

Сообщений: 210

05.05.2022, 21:55

3

Зачем в функцию чтения передавать копию контейнера и возвращать его, если она должна читать файл?

В функции записи нужно писать в созданный out, а не cout.



0



Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

Регистрация: 18.10.2014

Сообщений: 14,841

06.05.2022, 00:00

4

Цитата
Сообщение от Artemkcore
Посмотреть сообщение

Однако ofstream не хочет ни создавать новый файл, ни писать в существующий (код ниже, приведены лишь функции, которые могут касаться проблемы)

Так в где запись в файл в приведенном коде?



0



0 / 0 / 0

Регистрация: 11.09.2019

Сообщений: 4

06.05.2022, 00:12

 [ТС]

5

Ваше первое замечание совершенно справедливо, уже поправил

Но cout должен работать в этом случае, вот только дело до этого не доходит, проверка на то, открыт ли файл, не проходится, так как файл не создаётся либо не открывается

Добавлено через 1 минуту
Никаких ошибок или исключений при компиляции и работе не появляется



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

Регистрация: 18.10.2014

Сообщений: 14,841

06.05.2022, 00:22

6

Цитата
Сообщение от Artemkcore
Посмотреть сообщение

проверка на то, открыт ли файл, не проходится, так как файл не создаётся либо не открывается

Ну так а путь-то такой существует? Если пути не существует, то и файл не откроется.

Цитата
Сообщение от Artemkcore
Посмотреть сообщение

ios::out | ios::trunc

Комбинация избыточна. Достаточно просто ios::out. А так как это режим по умолчанию, вообще ничего указывать не нужно.

C++
1
out.open(a);

Отдельный вопрос — что за странная манера отдельно вызывать open для открытия файла, когда есть конструктор?

C++
1
2
    string a = "D:\путь к файлу\list.txt";
    ofstream out(a);



0



0 / 0 / 0

Регистрация: 11.09.2019

Сообщений: 4

06.05.2022, 00:24

 [ТС]

7

Цитата
Сообщение от TheCalligrapher
Посмотреть сообщение

Ну так а путь-то такой существует?

Конечно. Путь проверен десятки раз, все слэши экранированы

Добавлено через 1 минуту

Цитата
Сообщение от TheCalligrapher
Посмотреть сообщение

Комбинация избыточна. Достаточно просто ios::out. А так как это режим по умолчанию, вообще ничего указывать не нужно.

Я понимаю, что это скорее всего так, но это лишь один из множества испробованных вариантов



0



Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

Регистрация: 18.10.2014

Сообщений: 14,841

06.05.2022, 00:29

8

Цитата
Сообщение от Artemkcore
Посмотреть сообщение

Конечно. Путь проверен десятки раз, все слэши экранированы

Ну а если убрать нафиг путь из имени файла (то есть оставить только "list.txt" — пусть создается в текущем рабочем каталоге), то что тогда?



0



0 / 0 / 0

Регистрация: 11.09.2019

Сообщений: 4

06.05.2022, 00:50

 [ТС]

9

Цитата
Сообщение от TheCalligrapher
Посмотреть сообщение

Ну а если убрать нафиг путь из имени файла (то есть оставить только «list.txt» — пусть создается в текущем рабочем каталоге), то что тогда?

Да всё та же песня, не работает



0



zayats80888

5884 / 3288 / 1351

Регистрация: 07.02.2019

Сообщений: 8,309

06.05.2022, 00:59

10

Artemkcore, там либо нет прав для записи на диск, либо ты что-то не так делаешь
Скомпилируй и запусти этот пример, скажи какой будет вывод

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
 
void write(const char* name)
{
  std::ofstream out(name);
  out << 12345;
}
 
void read(const char* name)
{
  std::ifstream in(name);
  int i = 0;
  in >> i;
  std::cout << i << 'n';
}
 
int main()
{
  write("test.txt");
  read("test.txt");
}



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

06.05.2022, 00:59

Помогаю со студенческими работами здесь

Не открывает и не создает базу OpenOffice 4.1 (Java Jre)
Добрый день, привет всем!
Запускаю OpenOffice 4.1, выбираю создать новую базу данных, а она…

Матлаб не создает новые переменные,не открывает м-файлы
На экран выдает ошибки

??? Undefined function or method ‘workspacefunc’ for input arguments of…

Acronis не открывает *.tib файлы, которые сам же и создаёт?
Так-то не смешно уже. Сам создал, а открыть не может. Но всё по порядку.

Накрылся комп, цель-…

В папке OC создает подпапку 1, в которой создает текстовые файлы 1txt, 2txt Затем переименовывает файл 1txt в 3
bat в папке OC создает подпапку 1, в которой создает текстовые файлы 1.txt, 2.txt. Затем…

Вирус устанавливает программы, создает ярлыки, постоянно открывает браузер Амиго и вкладки с рекламой
Добрый день! скачала какой-то вирус, который постоянно устанавливает программы на компьютер,…

Написать bat-файл, который создает bat-файл, который создает текстовый файл :)
Необходимо составит bat файл, который создаст bat файл и в созданном новом bat файле создастся…

Не подключается заголовочный файл <ofstream>
Не понимаю, что не так с работой с файлами. Подскажите где ошибка и как исправить, пожалуйста….

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

10

Ok so im making a simple GUI program that tests the user, its crappy right now but only meant for debugging. Ok so here is all of my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "resource.h"
#include <fstream>

HINSTANCE hInst;

int right = 0;
int wrong = 0;


ofstream Score("Score.txt");

BOOL CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
        case WM_INITDIALOG:
            /*
             * TODO: Add code to initialize the dialog.
             */
            return TRUE;

        case WM_CLOSE:
            EndDialog(hwndDlg, 0);
            return TRUE;

        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case IDC_BTN_1:
                    right += 1;
                    return TRUE;

                case IDC_BTN_2:
                    wrong += 1;
                    return TRUE;

                case IDC_BTN_3:
                    right += 1;
                    return TRUE;

                case IDC_BTN_4:
                    wrong += 1;
                    return TRUE;

                case IDC_BTN_5:
                    right += 1;
                    return TRUE;

                case IDC_BTN_6:
                    wrong += 1;
                    return TRUE;

                case IDC_BTN_DONE:
                    MessageBox(hwndDlg, "Your score has been written to a text document labeled 'Score.txt'", "Information", MB_ICONINFORMATION);
                    Score << "Grand Theft Auto 4 Test Results" << std::endl;
                    Score << "=====================" << std::endl;
                    Score << "Number Right: " << right << std::endl;
                    Score << "Number Wrong: " << wrong << std::endl;
                    return TRUE;

                    //MessageBox(hwndDlg, "", "Information", MB_ICONINFORMATION);
            }
    }

    return FALSE;
}


int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hInst = hInstance;

    // The user interface is a modal dialog box
    return DialogBox(hInstance, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DialogProc);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "resource.h"

DLG_MAIN DIALOGEX 6, 5, 220, 350

CAPTION "GTA 4 Test"

FONT 8, "Tahoma"

STYLE 0x10CE0804

BEGIN
    CTEXT "Grand Theft Auto 4 Test", IDC_STATIC, 0, 0, 80, 15
    CTEXT "Written by Chay Hawk", IDC_STATIC, -3, 10, 80, 15
    CTEXT "In GTA 4 was the main character's name Niko?", IDC_STATIC, 50, 46, 150, 15
    CTEXT "In the game, did you have to rob a bank?", IDC_STATIC, 43, 82, 150, 15
    CTEXT "In the game is there 200 flying rats?", IDC_STATIC, 49, 116, 150, 15
    CONTROL "1. Yes", IDC_BTN_1, "Button", 0x10010000, 0,  35, 46, 15
    CONTROL "1. No", IDC_BTN_2, "Button", 0x10010000, 0, 52, 46, 15
    CONTROL "2. Yes", IDC_BTN_3, "Button", 0x10010000, 0, 70, 46, 15
    CONTROL "2. No", IDC_BTN_4, "Button", 0x10010000, 0, 88, 46, 15
    CONTROL "3. Yes", IDC_BTN_5, "Button", 0x10010000, 0, 105, 46, 15
    CONTROL "3. No", IDC_BTN_6, "Button", 0x10010000, 0, 122, 46, 15
    CONTROL "Done", IDC_BTN_DONE, "Button", 0x10010000, 0, 150, 46, 15
END
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <windows.h>

// ID of Main Dialog
#define DLG_MAIN 101

// ID of Button Controls
#define IDC_STATIC 1000
#define IDC_BTN_1 1001
#define IDC_BTN_2 1002
#define IDC_BTN_3 1003
#define IDC_BTN_4 1004
#define IDC_BTN_5 1005
#define IDC_BTN_6 1006
#define IDC_BTN_DONE 1007 

I use code blocks btw. Here are my errors:

C:UsersChay HawkDesktopGTA 4 Testmain.cpp|12|error: ‘ofstream’ does not name a type|
C:UsersChay HawkDesktopGTA 4 Testmain.cpp||In function ‘BOOL DialogProc(HWND__*, UINT, WPARAM, LPARAM)’:|
C:UsersChay HawkDesktopGTA 4 Testmain.cpp|57|error: ‘Score’ was not declared in this scope|
||=== Build finished: 2 errors, 0 warnings ===|

«THE LONG STORY; SHORT» — ANSWER

Since a std::fstream is not derived from either std::ofstream, nor std::ifstream, the reference is not «compatible» with the instance of std::fstream.

Use std::istream& and std::ostream&, instead of std::ifstream& and std::ofstream& (respectively).

void write_data (std::ostream&);
void  read_data (std::istream&);

INTRODUCTION

As the compiler is trying to tell you; std::fstream does not inherit from std::ifstream, therefore you cannot initialize a reference to the latter with a value of the former.

I’ve stumbled upon several developers who seem to assume that std::fstream, behind the scenes, is some sort of direct merge between a std::ifstream, and a std::ofstream, and that it is implemented by deriving from both.

When asked why they think that is the case, many think that the answer can be summed up with; «because it makes sense, right?»


THE SILLY ANALOGY

Imagine that we have three siblings; Ivan, Owen, and John, living in a family where reading and writing is everything.

All brothers were born with a gift;

  • Ivan is great at reading, and has given it his whole life, he never does anything else, and;
  • Owen has a thing for writing, which is odd since he can’t read, and;
  • John got lucky and got both the skill of reading and writing.

Just because John can do both of the things his brothers can, doesn’t mean that they are his parents — they are, after all; his brothers.

All three brothers has inherited their certain traits from other relatives, not each other.


THE ANSWER

std::fstream is not built «on top of» std::{i,o}fstream, even though they share certain parts of their individual inheritance tree.

iostreams inheritance visualized

src: http://en.cppreference.com/w/cpp/io

When accepting a stream in generic code you should not care about the «real» type of the underlying stream.

Does it really matter if we pass in a std::stringstream, std::fstream, or std::ofstream to our function which writes some output data to a stream? No, all we care about is the ability to read/write.

We express this by forming a reference to either std::istream, std::ostream, or std::iostream, when we need a stream which can;read, write, or both, respectively.

( Note: IF it’s not obvious: Ivan is an ifstream, Owen an ofstream, and John a fstream. )

Понравилась статья? Поделить с друзьями:
  • Officeclassicsetup ошибка 1603
  • Oct 7 ошибка старлайн а93
  • Officec2rclient exe системная ошибка apiclient dll
  • Ocs inventory service код ошибки 20
  • Office ошибка при перенаправлении команды приложению