Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Streams and files




Enum io_state

{

goodbit = 0x00;

eofbit = 0x01;

failbit = 0x02;

badbit = 0x04;

hardfail = 0x80;

};

For access to error status following functions can be used:

int rdstate(); returns current error status;

void clear(int i); sets error bit;

int good(); returns nono-zero when no errors;

int eof(); returns non-zero when end of file is reached;

int bad() return non-zero if badbit==1 or hardfail==1.

 

 

More simply the status of a stream can be checked in this way:

 

if (cin>>x) {   if (!cout) {
// successful input or // unsuccessful ouput
...   cerr<<”Something wwrong”<<”\n”;
}   }

 

This way is more elegant. It is possible due to overloading of operators! and void*:

int operator!();

operator void*();

Operator! returns non--zero value if bits failbit, badbit or hardfail are set.

Operator void*() converts the stream into the pointer. If failbit, badbit or hardfail are set this pointer will be NULL.

 

For streams of files the following hierarchy of cvlasses is used:

 

istream   ifstream    
      fstream
ostream   ofstream    

 

 

Classes ifstream and ofstream are described in <fstream.h> headr file.

 

EXAMPLE: program that copies text from file “complex.cpp” into file “target.cpp”, character by character.

 

#include <stdio.h>  
#include <fstream.h>  
main()  
{  
char ch;  
ifstream f1("complex.cpp");  
if (!f1) {  
cerr<<"Can't open file f1"<<"\n";  
}else{  
ofstream f2("target.cpp");  
if (!f2) {  
cerr<<"Can't create file f2"<<"\n";  
}else{  
while (f1.get(ch)) {f2.put(ch);};  
}  
}  
return 0;  
}  

 

If constructor failes to open file, it returns zero (!f1 or!f2 in our case). Destructors automatically will close files “complex.cpp” and “target.cpp”. Of course, destructors ~istream() and ~ofstream() are called automatically when program main() terminates.

 

The stream can be created with no connection to file. File name can be connected to stream later, during file opening:

 

ofstream of;  
of.open(“target.txt”); connection with file on disk
...  
of.close(); broke this connection

 

Following functions can be used for opening streams:

 

void ofstream::open(char* name, int=ios::out);

void ifstream::open(char* name, int=ios::in);

 

The first parameter is MS DOS file name. The second parameter defines opening mode:

 

ios::app append record to the end of file;
ios::ate open file and go to the end of file;
ios::in open file for input
ios::out open file for output
ios::trunc truncate file (make file length equal to zero)
ios::nocreate if file does not exists, opening doesn’t create it;

 

These modes are defined in class ios. Programmer can define several opening modes as disjunction of base modes:

 

fstream inout(“data.txt”,ios::in || ios::out);

inout<<i;




Поделиться с друзьями:


Дата добавления: 2014-11-28; Просмотров: 307; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.014 сек.