Esittely latautuu. Ole hyvä ja odota

Esittely latautuu. Ole hyvä ja odota

Tekstitiedostoon kirjoittaminen tMyn1 Tekstitiedostoon kirjoittaminen Tiedostoja käsitellään ohjelmassa tiedosto-olion avulla. Tiedosto-olion luokka sisältää.

Samankaltaiset esitykset


Esitys aiheesta: "Tekstitiedostoon kirjoittaminen tMyn1 Tekstitiedostoon kirjoittaminen Tiedostoja käsitellään ohjelmassa tiedosto-olion avulla. Tiedosto-olion luokka sisältää."— Esityksen transkriptio:

1 Tekstitiedostoon kirjoittaminen tMyn1 Tekstitiedostoon kirjoittaminen Tiedostoja käsitellään ohjelmassa tiedosto-olion avulla. Tiedosto-olion luokka sisältää jäsenfunktiot, joiden avulla tiedostoja on mahdollista käsitellä. Tiedosto-olion luokka edustaa tiedostotyyppiä, joka määrää tiedostonkäsittelytavan. Tiedostojen käsittelyssä tarvitaan fstream-, ifstream- ja ofstream-luokkia, jotka periytyvät tietovirtoja käsittelevistä istream- ja ostream-luokista, kuva 1.

2 Tekstitiedostoon kirjoittaminen tMyn2 ios_base ios istream iostream ostream streambuf cin cout, cerr, clog ifstream fstream ofstream filebuf istringstream stringstream ostringstream stringbuf Kuva 1. C++ -kielen syöttö- ja tulostusjärjestelmän luokkahierarkia.

3 Tekstitiedostoon kirjoittaminen tMyn3 Kuvasta 1 voidaan lukea edelleen, että kantaluokka on nimeltään ios_base, ja se on määritelty otsikkotiedostossa. ios_base –luokasta on johdettu luokka ios. ios –luokasta on edelleen johdettu luokat istream ja ostream. Kun ketjua jatkaa, niin löytää myös fstream-, ifstream- ja ofstream-luokat. Yhdessä kirjastossa voi olla määriteltynä useita luokkia, esim. otsikkotiedostossa on määritelty luokat ifstream, fstream, ofstream ja filebuf. Tiedostojen käsittelyä ajatellen kiinnostavimmat luokat ovat kuvassa 2:

4 Tekstitiedostoon kirjoittaminen tMyn4 Sequential and Random Input istream Sequential and Random Output ostream Tests and sets stream state ios File Output ofstream Sequential & Random Input/ Output iostream File Input/Output fstream File Input ifstream Records stream state, formatting controls ios_base Kuva 2. C++ -kielen syöttö- ja tulostusjärjestelmän keskeisimmät elementit.

5 Tekstitiedostoon kirjoittaminen tMyn5 Netistä selattuna huomataan, että tuo kuvan 2 luokkahierarkia on aikamoisen ”sekava”. Esim. luokka ios_base on ”tavallinen” luokka, kun taas vaikkapa luokka istream on ilmentymä (instance) mallista (template) basic_istream.

6 Tekstitiedostoon kirjoittaminen tMyn6 Käsitellään aluksi ofstream-olion avulla tulostamista (=kirjoittamista) tiedostoon käyttäen muotoiltua tulostusta (formatted output). Muotoiltu tulostus tarkoittaa sitä, että tulostettavat merkit (tässä siis tiedostoon kirjoitettavat merkit) tulostetaan tiedostoon käyttäen ylikuormitettua <<- operaattoria.

7 Tekstitiedostoon kirjoittaminen tMyn7 Kun aiemmin operoitiin cin- ja cout-olioiden kanssa, niin tarvittiin iostream-otsikkotiedosto. Nyt kun operoidaan tiedostojen kanssa, niin tarvitaan otsikkotiedostoksi fstream, siis #include Tuo otsikkotiedosto fstream sisältää datatyypit/luokat ofstream, ifstream ja fstream. Seuraavana askeleena työskenneltäessä tiedostojen kanssa on siis määriteltävä olio, joka on jokin noista kolmesta mainitusta tyypistä (tarpeen mukaan).

8 Tekstitiedostoon kirjoittaminen tMyn8 File Stream Data Type Description ofstream Output file stream. This data type can be used to create files and write data to them. With the ofstream data type, data may only be copied from variables to the file, but not vice versa. ifstream Input file stream. This data type can be used to open existing files and read data from them into memory. With the ifstream data type, data may only be copied from the file into variables, but not vice versa. fstream File stream. This data type can be used to create files, write data to them, and read data from them. With the fstream data type, data may be copied from variables into a file, or from a file into variables.

9 Tekstitiedostoon kirjoittaminen tMyn9 fstream: jos tiedostoa halutaan lukea ja sinne halutaan kirjoittaa avaamatta tiedostoa erikseen syöttö- ja tulostustiedostona. ifstream: jos tiedostosta halutaan pelkästään lukea. ofstream: jos tiedostoon halutaan pelkästään kirjoittaa.

10 Tekstitiedostoon kirjoittaminen tMyn10 Jos halutaan kirjoittaa tiedostoon d:\data\roskaa.txt (se tulee luoduksi aluksi), niin silloin luodaan olio ofstream jokunimi(”d:\\data\\roskaa.txt”);

11 Tekstitiedostoon kirjoittaminen tMyn11 ofstream Output file stream ios_base <- ios <- ostream <- ofstream ofstream provides an interface to write data to files as output streams. The objects of this class maintain internally a pointer to a filebuf object that can be obtained by calling member rdbuf. The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open. After all necessary operations on a file have been performed, it can be closed (or disassociated) by calling member close. Once closed, the same file stream object may be used to open another file. The member function is_open can be used to determine whether the stream object is currently associated with a file. Public members (constructor) Construct object and optionally open file (constructor member) rdbuf Get the associated filebuf object (public member function) is_open Check if a file is open (public member function) open Open file (public member function) close Close file (public member function)

12 Tekstitiedostoon kirjoittaminen tMyn12 Members inherited from ostream operator<< Insert data with format (public member function) put Put character (public member function) write Write block of data (public member function) tellp Get position of put pointer (public member function) seekp Set position of put pointer (public member function) flush Flush output stream buffer (public member function) sentry Perform exception safe prefix/suffix operations (public member classes) Member functions inherited from ios good Check if the state of the stream is good for i/o operations. (public member function) eof Check if eofbit is set (public member function) fail Check if either failbit or badbit is set (public member function) bad Check if badbit is set (public member function) operator! Evaluate stream object (public member function) operator void* Convert to pointer (public member function) rdstate Get error state flags (public member function) setstate Set error state flag (public member function) clear Set error state flags (public member function) copyfmt Copy formatting information (public member functions) fill Get/set the fill character (public member function) exceptions Get/set exception mask (public member function) imbue Imbue locale (public member function) tie Get/set the tied stream (public member function) narrow Narrow character (public member function) widen Widen character (public member function)

13 Tekstitiedostoon kirjoittaminen tMyn13 Member functions inherited from ios_base flags Get/set format flags (public member function) setf Set specific format flags (public member function) unsetf Clear specific format flags (public member function) precision Get/Set floating-point decimal precision (public member function) width Get/set field width (public member function) imbue Imbue locale (public member function) getloc Get current locale (public member function) xalloc Return a new index for the internal extensible array [static] (public static member function) iword Get reference to integer element of the internal extensible array (public member function) pword Get reference to pointer of the internal extensible array (public member function) register callback Register event callback function (public member function) sync_with_stdio Activate/deactivate synchronization of iostream and cstdio streams [static] (public static member function)

14 Tekstitiedostoon kirjoittaminen tMyn14 ifstream Input file stream class ios_base <- ios <- istream <- ifstream ifstream provides an interface to read data from files as input streams. The objects of this class maintain internally a pointer to a filebuf object that can be obtained by calling member rdbuf. The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open. After all necessary operations on a file have been performed, it can be closed (or disassociated) by calling member close. Once closed, the same file stream object may be used to open another file. The member function is_open can be used to determine whether the stream object is currently associated with a file. Public members (constructor) Construct object and optionally open file (constructor member) rdbuf Get the associated filebuf object (public member function) is_open Check if a file is open (public member function) open Open file (public member function) close Close file (public member function)

15 Tekstitiedostoon kirjoittaminen tMyn15 Members inherited from istream operator>> Extract formatted data (public member function) gcount Get number of characters extracted by last unformatted input operation (public member function) get Get unformatted data from stream (public member function) getline Get line from stream (public member function) ignore Extract and discard characters (public member functions) peek Peek next character (public member function) read Read block of data (public member function) readsome Read block of data available in the buffer (public member function) putback Put character back (public member function) unget Decrement get pointer (public member function) tellg Get position of the get pointer. (public member function) seekg Set position of the get pointer (public member function) sync Synchronize input buffer with source of characters (public member function) sentry Perform exception safe prefix/suffix operations (public member class)

16 Tekstitiedostoon kirjoittaminen tMyn16 Member functions inherited from ios good Check if the state of the stream is good for i/o operations. (public member function) eof Check if eofbit is set (public member function) fail Check if either failbit or badbit is set (public member function) bad Check if badbit is set (public member function) operator! Evaluate stream object (public member function) operator void* Convert to pointer (public member function) rdstate Get error state flags (public member function) setstate Set error state flag (public member function) clear Set error state flags (public member function) copyfmt Copy formatting information (public member functions) fill Get/set the fill character (public member function) exceptions Get/set exception mask (public member function) imbue Imbue locale (public member function) tie Get/set the tied stream (public member function) narrow Narrow character (public member function) widen Widen character (public member function)

17 Tekstitiedostoon kirjoittaminen tMyn17 Member functions inherited from ios_base flags Get/set format flags (public member function) setf Set specific format flags (public member function) unsetf Clear specific format flags (public member function) precision Get/Set floating-point decimal precision (public member function) width Get/set field width (public member function) imbue Imbue locale (public member function) getloc Get current locale (public member function) xalloc Return a new index for the internal extensible array [static] (public static member function) iword Get reference to integer element of the internal extensible array (public member function) pword Get reference to pointer of the internal extensible array (public member function) register_callback Register event callback function (public member function) sync_with_stdio Activate/deactivate synchronization of iostream and cstdio streams [static] (public static member function)

18 Tekstitiedostoon kirjoittaminen tMyn18 fstream Input/output file stream class ios_base <- ios <- istream <- iostream <- fstream <- ostream <- fstream provides an interface to read and write data from files as input/output streams. The objects of this class maintain internally a pointer to a filebuf object that can be obtained by calling member rdbuf. The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open. After all necessary operations on a file have been performed, it can be closed (or disassociated) by calling member close. Once closed, the same file stream object may be used to open another file. The member function is_open can be used to determine whether the stream object is currently associated with a file. Public members (constructor) Construct object and optionally open file (constructor member) rdbuf Get the associated filebuf object (public member function) is_open Check if a file is open (public member function) open Open file (public member function) close Close file (public member function)

19 Tekstitiedostoon kirjoittaminen tMyn19 Members inherited from istream operator>> Extract formatted data (public member function) gcount Get number of characters extracted by last unformatted input operation (public member function) get Get unformatted data from stream (public member function) getline Get line from stream (public member function) ignore Extract and discard characters (public member functions) peek Peek next character (public member function) read Read block of data (public member function) readsome Read block of data available in the buffer (public member function) putback Put character back (public member function) unget Decrement get pointer (public member function) tellg Get position of the get pointer. (public member function) seekg Set position of the get pointer (public member function) sync Synchronize input buffer with source of characters (public member function) sentry Perform exception safe prefix/suffix operations (public member class)

20 Tekstitiedostoon kirjoittaminen tMyn20 Members inherited from ostream operator<< Insert data with format (public member function) put Put character (public member function) write Write block of data (public member function) tellp Get position of put pointer (public member function) seekp Set position of put pointer (public member function) flush Flush output stream buffer (public member function) sentry Perform exception safe prefix/suffix operations (public member classes)

21 Tekstitiedostoon kirjoittaminen tMyn21 Member functions inherited from ios good Check if the state of the stream is good for i/o operations. (public member function) eof Check if eofbit is set (public member function) fail Check if either failbit or badbit is set (public member function) bad Check if badbit is set (public member function) operator! Evaluate stream object (public member function) operator void* Convert to pointer (public member function) rdstate Get error state flags (public member function) setstate Set error state flag (public member function) clear Set error state flags (public member function) copyfmt Copy formatting information (public member functions) fill Get/set the fill character (public member function) exceptions Get/set exception mask (public member function) imbue Imbue locale (public member function) tie Get/set the tied stream (public member function) narrow Narrow character (public member function) widen Widen character (public member function)

22 Tekstitiedostoon kirjoittaminen tMyn22 Member functions inherited from ios_base flags Get/set format flags (public member function) setf Set specific format flags (public member function) unsetf Clear specific format flags (public member function) precision Get/Set floating-point decimal precision (public member function) width Get/set field width (public member function) imbue Imbue locale (public member function) getloc Get current locale (public member function) xalloc Return a new index for the internal extensible array [static] (public static member function) iword Get reference to integer element of the internal extensible array (public member function) pword Get reference to pointer of the internal extensible array (public member function) register_callback Register event callback function (public member function) sync_with_stdio Activate/deactivate synchronization of iostream and cstdio streams [static] (public static member function)

23 Tekstitiedostoon kirjoittaminen tMyn23 Tiedoston luonti ja avaus erikseen open- jäsenfunktiolla: luokka tiedosto; tiedosto.open(tiedostonNimi, avaustapa);

24 Tekstitiedostoon kirjoittaminen tMyn24 luokka on jokin luokista fstream, ifstream tai ofstream. tiedosto on ohjelmassa käytettävä nimi tiedosto- oliosta. Tiedoston luonti ja avaus yhdessä: luokka tiedosto(tiedostonNimi, avaustapa); Seuraavassa esimerkkiohjelma, jossa kirjoitetaan lukuja tiedostoon, avaustapaa ei määritellä vaan tyydytään oletusarvoon.

25 Tekstitiedostoon kirjoittaminen tMyn25 Jos tiedostoa ei ole olemassa, niin sitten ohjelma luo sellaisen. Jos tiedosto on olemassa, niin sitten vanha sisältö menetetään. Jos tiedostoa ei luoda juureen, niin sitten hakemisto, mihin tiedosto tallennetaan, on oltava olemassa. Ohjelma ei pysty luomaan hakemistoa. Huomaa hakemistopolun kirjoittamisen syntaksi! Ohjelma ei tulosta mitään näytölle, mutta esim. Notepad:llä voi käydä katsomassa miten luonnin kanssa kävi:

26 Tekstitiedostoon kirjoittaminen tMyn26 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const int max=150; ofstream kirjoitetaan("d:\\data\\emailit\\roskaa.txt"); for (int i=0; i<max; i++) { if (i%5 == 0) kirjoitetaan<<endl; kirjoitetaan<<setw(5)<<i; } return 0; }

27 Tekstitiedostoon kirjoittaminen tMyn27

28 Tekstitiedostoon kirjoittaminen tMyn28 Eli tähän mennessä on nähty lukematon kerta insertio-operaattorin (<<) käyttämisestä cout-olion kanssa tulostettaessa tietoa oletusoutputtiin eli näytölle. Nyt edellisessä esimerkissä samaista operaattoria (<<) käytettiin ofstream-luokan olion ’kirjoitetaan’ kanssa kirjoittamaan tietoa tiedostoon. Jos edellä olevan ohjelman suorittaa toisen kerran, niin aiempi tallennus tuhoutuu. Onneksi tiedoston avaustapoja on useita. Seuraavassa näistä tavoista yhteenveto taulukkona. Niitä kaikkia voidaan käyttää silloin, kun tiedosto- olion luokkana on fstream.

29 Tekstitiedostoon kirjoittaminen tMyn29 File Access Flag Meaning ios::appAppend mode. If the file already exists, its contents are preserved and all output is written to the end of the file. By default, this flag causes the file to be created if it does not exist. ios::ateIf the file already exists, the program goes directly to the end of it. Output may be written anywhere in the file. ios::binaryBinary mode. When a file is opened in binary mode, data are written to or read from it in pure binary format. (The default mode is text) ios::inInput mode. Data will be read from the file. If the file does not exist, it will not be created and the open function will fail. ios::outOutput mode. Data will be written to the file. By default, the file’s contents will be deleted if it already exists. ios::truncIf the file already exists, its contents will be deleted (truncated). This is the default mode used by ios::out.

30 Tekstitiedostoon kirjoittaminen tMyn30 ios::inAvaus tiedoston lukemista varten. Oletusarvo ifstream- luokan oliolle ios::outAvaus tiedostoon kirjoittamista varten. Oletusarvo ofstream-luokan oliolle. Jos tiedosto on jo olemassa, vanhat tiedot tuhoutuvat. ios::out | ios::appAvaus tiedostoon kirjoittamista varten vanhoja tietoja tuhoamatta. Uudet tiedot kirjoitetaan tiedoston loppuun vanhojen tietojen perään. ios::out | ios::ateOsoitin siirtyy avauksen yhteydessä tiedoston loppumerkkiin. Avauslippuja voidaan yhdistää tai-operaattorilla:

31 Tekstitiedostoon kirjoittaminen tMyn31 ios::out | ios::truncLuo uuden tiedoston avattaessa. Jos tiedosto oli olemassa, niin vanhat tiedot tuhoutuvat. ios::in | ios::outAvaus tiedostoon kirjoittamista ja tiedoston lukemista varten. Jos tiedosto oli olemassa, vanhat tiedot säilyvät. ios::in | ios::out | ios::trunc Avaus tiedostoon kirjoittamista ja tiedoston lukemista varten. Jos tiedosto oli olemassa, vanhat tiedot tuhoutuvat. jokin edellisistä | ios::binary Tiedoston käsittely binaarisena.

32 Tekstitiedostoon kirjoittaminen tMyn32 ios_base::openmode Type for stream opening mode flags Bitmask type to represent stream opening mode flags. A value of this type can be any valid combination of the following member constants: app(append) Set the stream's position indicator to the end of the stream before each output operation. ate(at end) Set the stream's position indicator to the end of the stream on opening. binary(binary) Consider stream as binary rather than text. in(input) Allow input operations on the stream. out(output) Allow output operations on the stream. trunc(truncate) Any current content is discarded, assuming a length of zero on opening. These constants are defined in the ios_base class as public members. Therefore, they can be refered to either directly by their name as ios_base members (like ios_base::in) or by using any of their inherited classes or instantiated objects, like for example ios::ate or cout.out.

33 Tekstitiedostoon kirjoittaminen tMyn33 Luokilla ifstream ja ofstream on oletusarvot sille, miten ne avaavat tiedoston ja mitä tiedostossa olevalle vanhalle tiedolle tapahtuu:

34 Tekstitiedostoon kirjoittaminen tMyn34 File TypeDefault Open Mode ofstreamThe file is opened for output only. Data may be written to the file, but not read from the file. If the file does not exist, it is created. If the file already exists, its contents are deleted (the file is truncated). ifstreamThe file is opened for input only. Data may be read from the file, but not written to it. The file’s contents will be read from the beginning. If the file does not exist, the open function fails.

35 Tekstitiedostoon kirjoittaminen tMyn35 Siis taulukosta luettuna: jos olion luokkana on ofstream, niin silloin tiedostoon voi vain kirjoittaa. Tuota tosiasiaa ei voi muuttaa, mutta sitä vastoin toimintaa voi ”hienosäätää” avauslipuilla vaikkapa näin: ofstream kirjoitetaan; kirjoitetaan.open(”roskaa.txt”, ios::out | ios::app); Nyt siis vanhat tiedot eivät tuhoudu – niin kuin tapahtuisi oletustoiminnassa, vaan uusi tieto lisätään olemassaolevan tiedon loppuun.

36 Tekstitiedostoon kirjoittaminen tMyn36 Muunnetaan aiempaa tehtävää siten, että nyt tulostiedosto avataan vanhoja tietoja tuhoamatta, ja uudet tiedot kirjoitetaan tiedoston loppuun:

37 Tekstitiedostoon kirjoittaminen tMyn37 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const int max=50; ofstream kirjJatkoksi("d:\\data\\emailit\\roskaa.txt", ios::out | ios::app); for (int i=0; i<max; i++) { if (i%5==0) kirjJatkoksi<<endl; kirjJatkoksi<<setw(5)<<i; } return 0; }

38 Tekstitiedostoon kirjoittaminen tMyn38

39 Tekstitiedostoon kirjoittaminen tMyn39 Tiedoston avauksen jälkeen voidaan testata, onnistuiko tiedoston avaus: if (tiedosto.is_open())… if (!tiedosto.fail())… if (tiedosto.good())… Muutetaan aikaisempaa esimerkkiä siten, että yritetään avata tiedosto sellaiseen hakemistoon, jota vielä ei ole olemassa. Se ei onnistu:

40 Tekstitiedostoon kirjoittaminen tMyn40 bool good ( ) const; Check if the state of the stream is good for i/o operations. The function returns true if none of the stream's error flags (eofbit, failbit and badbit) are set. bool fail ( ) const; Check if either failbit or badbit is set The function returns true if either the failbit or the badbit is set. At least one of these flags is set when some error other than reaching the End-Of-File occurs during an input operation. bool is_open ( ); Check if a file is open Returns true if the stream is currently associated with a file, and false otherwise.

41 Tekstitiedostoon kirjoittaminen tMyn41 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const int max=60; ofstream kirjJatkoksi("d:\\eiOlemassa\\emailit\\roskaa.txt", ios::out | ios::app);

42 Tekstitiedostoon kirjoittaminen tMyn42 if(kirjJatkoksi.good()) { for (int i=0; i<max; i++) { if (i%5==0) kirjJatkoksi<<endl; kirjJatkoksi<<setw(5)<<i; } else cout<<"Tiedoston avaus ei onnistunut!"<<endl; return 0; }

43 Tekstitiedostoon kirjoittaminen tMyn43 Tiedoston sulkeminen toteutetaan komennolla tiedosto.close(); Tiedoston sulkeminen ei poista tiedosto-oliota. Samaan tiedosto-olioon voidaan myöhemmin liittää sama tai eri tiedosto open()-jäsenfunktiolla. Tiedosto-olio katoaa joka tapauksessa, kun ohjelman suoritus päättyy, mutta on hyvän tavan mukaista sulkea tiedosto close-funktiolla.

44 Tekstitiedostoon kirjoittaminen tMyn44 On olemassa kaksi tapaa, joilla voidaan lukea tietoa virrasta tai kirjoittaa tietoa virtaan. Tähän asti olleissa esimerkeissä tiedon kirjoittamisessa tiedostoon on käytetty tapaa, jossa erityyppistä tietoa kirjoitetaan (ja vastaavasti luettaisiin) >-operaattoreiden avulla. Ne ovat muotoiltuja syöttö/tulostusoperaatioita. Nämä operaatiot voivat olla teksti- tai binaarimuodossa, mutta yleisemmin ne suoritetaan tekstimuodossa.

45 Tekstitiedostoon kirjoittaminen tMyn45 Toinen virtojen käyttötapa on lukea tai kirjoittaa muotoilematonta tietoa (unformatted stream). Luku- tai kirjoitusoperaatio voi kohdistua yhteen merkkiin, tiettyyn määrään merkkejä tai merkkijoukkoon, jonka päättää jonkinlainen erotinmerkki. Kaikkein tärkeintä tässä käyttötavassa on mahdollisuus lukea tai kirjoittaa tavuja. Nämä ovat muotoilemattomia syöttö/tulostusoperaatioita (unformatted stream operations).

46 Tekstitiedostoon kirjoittaminen tMyn46 Monien syöttöfunktioiden vastakohtana muotoilemattomia tulostusfunktioita (joilla siis tietoa kirjoitetaan tiedostoon) on vain kaksi (unformatted stream output): ostream& put(char ch) ostream& write(const char* pTaulukko, streamsize n) Tehdään esimerkkiohjelma, joka tallentaa näppäimistöltä annetun tekstin merkkivakio kerrallaan. Lopuksi tiedosto suljetaan:

47 Tekstitiedostoon kirjoittaminen tMyn47 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { char merkki; ofstream kirjJatkoksi("d:\\data\\Emailit\\roskaa2.txt", ios_base::out | ios_base::app); if(kirjJatkoksi.good()) { cout<<"Kirjoita teksti\204 ja kun haluat lopettaa, "<<endl <<"niin paina ENTER ja sen j\204keen CTRL-C:\n"; cin.get(merkki);

48 Tekstitiedostoon kirjoittaminen tMyn48 while(merkki!=EOF) { if(merkki=='\204') kirjJatkoksi.put('ä'); else if(merkki=='\224') kirjJatkoksi.put('ö'); else kirjJatkoksi.put(merkki); cin.get(merkki); } kirjJatkoksi.close(); } else cout<<"Tiedoston avaus ei onnistunut!!"; return 0; }

49 Tekstitiedostoon kirjoittaminen tMyn49

50 Tekstitiedostoon kirjoittaminen tMyn50 Edellisessä esimerkissä käytettiin while-rakenteessa EOF-merkkiä, joka siis vastaa näppäimistöltä syötettyä tiedoston lopetusmerkkiä CTRL-C. Jos tuota EOF-symbolia vierastaa, niin voidaan käyttää vanhaan tyyliin testiä merkkien loppumisesta. Milloin tarkasti ottaen kirjoitus tiedostoon tapahtuu? Tehdään testi:

51 Tekstitiedostoon kirjoittaminen tMyn51 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { char merkki; int lkm=0; ofstream kirjJatkoksi("d:\\data\\Emailit\\roskaa2a.txt", ios_base::out | ios_base::app); if(kirjJatkoksi.good()) { cout<<"Kirjoita teksti\204 ja kun haluat lopettaa, "<<endl <<"niin paina ENTER ja sen j\204keen CTRL-C\n";

52 Tekstitiedostoon kirjoittaminen tMyn52 while(cin.get(merkki)) { lkm=lkm+1; cout<<lkm<<endl; if(merkki=='\204') kirjJatkoksi.put('ä'); else if(merkki=='\224') kirjJatkoksi.put('ö'); else kirjJatkoksi.put(merkki); } kirjJatkoksi.close(); } else cout<<"Tiedoston avaus ei onnistunut!!"; return 0; }

53 Tekstitiedostoon kirjoittaminen tMyn53 Painetaan Enter, ja lauseen luulisi tallentuvan tiedostoon, mutta niin ei tapahdu!

54 Tekstitiedostoon kirjoittaminen tMyn54 Eli tarvittiin se CTRL-C


Lataa ppt "Tekstitiedostoon kirjoittaminen tMyn1 Tekstitiedostoon kirjoittaminen Tiedostoja käsitellään ohjelmassa tiedosto-olion avulla. Tiedosto-olion luokka sisältää."

Samankaltaiset esitykset


Iklan oleh Google