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
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
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
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 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
4672 gold badges8 silver badges20 bronze badges
answered Jul 17, 2021 at 14:24
1
I faced the same error because I forgot to use using namespace std;
after including it, the problem was solved.
answered Apr 6, 2021 at 5:10
1
Artemkcore 0 / 0 / 0 Регистрация: 11.09.2019 Сообщений: 4 |
||||
1 |
||||
05.05.2022, 21:22. Показов 1486. Ответов 9 Метки c++, ofstream (Все метки)
Здравствуйте!
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.05.2022, 21:22 |
Ответы с готовыми решениями: Команда fopen не создает/ не открывает файл В одной делаю простой код: #include <stdio.h> Студия не создает и не открывает проекты Составить программу, которая создает каталог, создает в нем файл, переименовывает этот файл и удаляет этот файл, а потом удаляет каталог 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 |
Вездепух 10908 / 5905 / 1613 Регистрация: 18.10.2014 Сообщений: 14,841 |
|
06.05.2022, 00:00 |
4 |
Однако ofstream не хочет ни создавать новый файл, ни писать в существующий (код ниже, приведены лишь функции, которые могут касаться проблемы) Так в где запись в файл в приведенном коде?
0 |
0 / 0 / 0 Регистрация: 11.09.2019 Сообщений: 4 |
|
06.05.2022, 00:12 [ТС] |
5 |
Ваше первое замечание совершенно справедливо, уже поправил Но cout должен работать в этом случае, вот только дело до этого не доходит, проверка на то, открыт ли файл, не проходится, так как файл не создаётся либо не открывается Добавлено через 1 минуту
0 |
TheCalligrapher Вездепух 10908 / 5905 / 1613 Регистрация: 18.10.2014 Сообщений: 14,841 |
||||||||
06.05.2022, 00:22 |
6 |
|||||||
проверка на то, открыт ли файл, не проходится, так как файл не создаётся либо не открывается Ну так а путь-то такой существует? Если пути не существует, то и файл не откроется.
ios::out | ios::trunc Комбинация избыточна. Достаточно просто
Отдельный вопрос — что за странная манера отдельно вызывать
0 |
0 / 0 / 0 Регистрация: 11.09.2019 Сообщений: 4 |
|
06.05.2022, 00:24 [ТС] |
7 |
Ну так а путь-то такой существует? Конечно. Путь проверен десятки раз, все слэши экранированы Добавлено через 1 минуту
Комбинация избыточна. Достаточно просто ios::out. А так как это режим по умолчанию, вообще ничего указывать не нужно. Я понимаю, что это скорее всего так, но это лишь один из множества испробованных вариантов
0 |
Вездепух 10908 / 5905 / 1613 Регистрация: 18.10.2014 Сообщений: 14,841 |
|
06.05.2022, 00:29 |
8 |
Конечно. Путь проверен десятки раз, все слэши экранированы Ну а если убрать нафиг путь из имени файла (то есть оставить только
0 |
0 / 0 / 0 Регистрация: 11.09.2019 Сообщений: 4 |
|
06.05.2022, 00:50 [ТС] |
9 |
Ну а если убрать нафиг путь из имени файла (то есть оставить только «list.txt» — пусть создается в текущем рабочем каталоге), то что тогда? Да всё та же песня, не работает
0 |
zayats80888 5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,309 |
||||
06.05.2022, 00:59 |
10 |
|||
Artemkcore, там либо нет прав для записи на диск, либо ты что-то не так делаешь
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
06.05.2022, 00:59 |
Помогаю со студенческими работами здесь Не открывает и не создает базу OpenOffice 4.1 (Java Jre) Матлаб не создает новые переменные,не открывает м-файлы ??? Undefined function or method ‘workspacefunc’ for input arguments of… Acronis не открывает *.tib файлы, которые сам же и создаёт? Накрылся комп, цель-… В папке OC создает подпапку 1, в которой создает текстовые файлы 1txt, 2txt Затем переименовывает файл 1txt в 3 Вирус устанавливает программы, создает ярлыки, постоянно открывает браузер Амиго и вкладки с рекламой Написать 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:
|
|
|
|
|
|
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.
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. )