Esittely latautuu. Ole hyvä ja odota

Esittely latautuu. Ole hyvä ja odota

Tekstitiedostosta lukeminen tMyn1 Tekstitiedostosta lukeminen Tiedosto voidaan avata pelkästään lukemista varten tai kirjoittamista ja lukemista varten.

Samankaltaiset esitykset


Esitys aiheesta: "Tekstitiedostosta lukeminen tMyn1 Tekstitiedostosta lukeminen Tiedosto voidaan avata pelkästään lukemista varten tai kirjoittamista ja lukemista varten."— Esityksen transkriptio:

1 Tekstitiedostosta lukeminen tMyn1 Tekstitiedostosta lukeminen Tiedosto voidaan avata pelkästään lukemista varten tai kirjoittamista ja lukemista varten. Jos tiedosto avataan pelkästään lukemista varten, voidaan luoda tiedosto-olio ifstream-luokkaan: ifstream tiedosto(ulkoinenNimi);

2 Tekstitiedostosta lukeminen tMyn2 Tiedoston loppumista voidaan testata peek- ja eof- jäsenfunktioilla: if (tiedosto.peek()==EOF) … if(tiedosto.eof()) …

3 Tekstitiedostosta lukeminen tMyn3 istreampublic member function: int peek ( ); Peek next character Reads and returns the next character without extracting it, i.e. leaving it as the next character to be extracted from the stream. Parameters none Return Value The value of the next character. In the case of error, the function returns EOF (or traits::eof() for other traits) and modifies the state flags accordingly: flagerror eofbitThe end of the source of characters is reached during its operations. failbit- badbitAn error other than the above happened. Additionaly, in any of these cases, if the appropriate flag has been set with member function ios::exceptions, an exception of type ios_base::failure is thrown.

4 Tekstitiedostosta lukeminen tMyn4 ios public member function: bool eof ( ) const; Check if eofbit is set The function returns true if the eofbit stream's error flag has been set by a previous i/o operation. This flag is set by all standard input operations when the End Of File is reached in the sequence associated with the stream. Parameters none Return Value true if eofbit stream's state flag is set (which signals that the End-of-File has been reached). false otherwise.

5 Tekstitiedostosta lukeminen tMyn5 Seuraavassa esimerkissä luetaan näytölle tiedostoon tallennetut luvut käyttäen muotoiltua syöttöoperaatiota (formatted input). Käytetään siis tähän tehtävään ylikuormitettua >>-operaattoria. Olkoot tiedoston sisältö seuraavanlainen:

6 Tekstitiedostosta lukeminen tMyn6

7 Tekstitiedostosta lukeminen tMyn7 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const char* tiedNimi="d:\\data\\emailit\\roskaa.txt"; ifstream taaltaLuetaan(tiedNimi); if(!taaltaLuetaan) { cout<<"Tiedoston "<<tiedNimi <<" avaus ep\204onnistui"; exit(1); }

8 Tekstitiedostosta lukeminen tMyn8 int luku=0; int monesko=0; while(!taaltaLuetaan.eof()) { taaltaLuetaan>>luku; cout<<(monesko++ % 5==0 ? "\n" : "") <<setw(5)<<luku; } cout<<endl; return 0; }

9 Tekstitiedostosta lukeminen tMyn9 Näytölle tulostuu:

10 Tekstitiedostosta lukeminen tMyn10 istream-luokassa on määritelty runsaasti muotoilemattomia syöttöfunktioita (unformatted input), ja ne on periytetty ifstream-, iostream- ja fstream-luokkiin. get()-jäsenfunktiosta on useita muotoja, kts. jäljessä olevia poimintoja netistä. Lisäksi käytössä on mm. kaksi getline()- jäsenfunktiota.

11 Tekstitiedostosta lukeminen tMyn11 istreamclass Input stream ios_base <- ios <- istream <- iostream <- ifstream <- istringstream istream objects are stream objects used to read and interpret input from sequences of characters. Specific members are provided to perform these input operations, which can be divided in two main groups: Formatted input These functions extract data from a sequence of characters that may be interpreted and formatted to a value of a certain type. These type of operation is performed using member and global functions that overload the extraction operator (operator >>).

12 Tekstitiedostosta lukeminen tMyn12 Unformatted input Most of the other member functions of the istream class are used to perform unformatted input, i.e. no interpretation is made on the characters got form the input. These member functions can get a determined number of characters from the input character sequence (get, getline, peek, read, readsome), manipulate the get pointer (ignore, seekg, tellg, unget) or get information of the last unformatted input operation (gcount). Additionaly, a member function exists to synchronize the stream with the associated external source of characters: sync. The standard object cin is an instantiation of this class. The class inherits all the internal fields from its parent classes ios_base and ios:

13 Tekstitiedostosta lukeminen tMyn13 Formatting information  format flags: a set of internal indicators describing how certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.  field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.  display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.  fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.

14 Tekstitiedostosta lukeminen tMyn14  locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue. State information  error state: internal indicator reflecting the integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.  exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions. Other  event function stack: stack of pointers to callback functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.

15 Tekstitiedostosta lukeminen tMyn15  internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.  pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.  pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

16 Tekstitiedostosta lukeminen tMyn16 Public members (destructor)Destruct object (destructor member) (constructor)Construct object (constructor member) Formatted input: operator>>Extract formatted data (public member function)

17 Tekstitiedostosta lukeminen tMyn17 Unformatted input: gcountGet number of characters extracted by last unformatted input operation (public member function) getGet unformatted data from stream (public member function) getlineGet line from stream (public member function) ignoreExtract and discard characters (public member functions) peekPeek next character (public member function) readRead block of data (public member function) readsome Read block of data available in the buffer (public member function) putbackPut character back (public member function) ungetDecrement get pointer (public member function)

18 Tekstitiedostosta lukeminen tMyn18 Positioning: tellgGet position of the get pointer. (public member function) seekgSet position of the get pointer (public member function) Synchronization: syncSynchronize input buffer with source of characters (public member function) Prefix/Suffix: sentryPerform exception safe prefix/suffix operations (public member class)

19 Tekstitiedostosta lukeminen tMyn19 Member functions inherited from ios goodCheck if the state of the stream is good for i/o operations. (public member function) eofCheck if eofbit is set (public member function) failCheck if either failbit or badbit is set (public member function) badCheck if badbit is set (public member function) operator!Evaluate stream object (public member function) operator void*Convert to pointer (public member function) rdstateGet error state flags (public member function) setstateSet error state flag (public member function) clearSet error state flags (public member function) copyfmtCopy formatting information (public member functions)

20 Tekstitiedostosta lukeminen tMyn20 fillGet/set the fill character (public member function) exceptionsGet/set exception mask (public member function) imbueImbue locale (public member function) tieGet/set the tied stream (public member function) rdbufGet/set the associated stream buffer (public member function) narrowNarrow character (public member function) widenWiden character (public member function)

21 Tekstitiedostosta lukeminen tMyn21 Member functions inherited from ios_base flagsGet/set format flags (public member function) setfSet specific format flags (public member function) unsetfClear specific format flags (public member function) precision Get/Set floating-point decimal precision (public member function) widthGet/set field width (public member function) imbueImbue locale (public member function) getlocGet current locale (public member function)

22 Tekstitiedostosta lukeminen tMyn22 xallocReturn a new index for the internal extensible array [static] (public static member function) iwordGet reference to integer element of the internal extensible array (public member function) pwordGet 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 Tekstitiedostosta lukeminen tMyn23 istream::getpublic member function int get(); istream& get ( char& c ); istream& get ( char* s, streamsize n ); istream& get ( char* s, streamsize n, char delim ); istream& get ( streambuf& sb); istream& get ( streambuf& sb, char delim ); Get unformatted data from stream These member functions perform unformatted input operations. Depending on the type and number of arguments the function behaves in the following way:

24 Tekstitiedostosta lukeminen tMyn24 int get(); Extracts a character from the stream and returns its value (casted to an integer). istream& get ( char& c ); Extracts a character from the stream and stores it in c. istream& get (char* s, streamsize n ); Extracts characters from the stream and stores them as a c-string into the array beginning at s. Characters are extracted until either (n - 1) characters have been extracted or the delimiting character '\n' is found. The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation. If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline

25 Tekstitiedostosta lukeminen tMyn25 if you want this character to be extracted (and discarded). The ending null character that signals the end of a c-string is automatically appended at the end of the content stored in s. istream& get (char* s, streamsize n, char delim ); Same as above, except that the delimiting character is the one specified indelim instead of '\n'. istream& get (streambuf& sb); Extracts characters from the stream and inserts them in the stream buffer sb until either the delimiting character '\n' is found or end of file is reached. The extraction also stops if an error occurs either in the input sequence controled by the stream or in the output sequence controlled by sb. istream& get (streambuf& sb, char delim );

26 Tekstitiedostosta lukeminen tMyn26 Same as above, except that the delimiting character is the one specified indelim instead of '\n'. The number of characters read by any of the previous input operations can be obtained by calling to the member function gcount. Parameters c A char variable to store the extracted character. s A pointer to an array of characters where the string is stored as a c-string n Maximum number of characters to store (including the ternimating null character). This is an integer value of type streamsize.

27 Tekstitiedostosta lukeminen tMyn27 delim The delimiting character. The operation of extracting succesive characters is stopped when this character is read. This parameter is optional, if not specified the function considers '\n' (a newline character) to be the delimiting character. sb An output stream buffer (an object of class streambuf or any of its derived classes). Return Value For the first prototype, the function returns the character read. For the remaining prototypes, the function return *this. Errors are signaled by modifying the internal state flags:

28 Tekstitiedostosta lukeminen tMyn28 flagerror eofbitThe end of the source of characters is reached during its operations. failbitNo characters were extracted because either the end was prematurely found or the insertion operation in the destination failed (this only applies to the streambuf case). Notice that some eofbit cases will also set failbit. badbitAn error other than the above happened. Additionaly, in any of these cases, if the appropriate flag has been set with member function ios::exceptions, an exception of type ios_base::failure is thrown.

29 Tekstitiedostosta lukeminen tMyn29 istream::getlinepublic member function istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim ); Get line from stream Extracts characters from the input sequence and stores them as a c-string into the array beginning at s. Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or '\n' otherwise). The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation. If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it. If you don't want this character to be extracted, you can use member get instead.

30 Tekstitiedostosta lukeminen tMyn30 The ending null character that signals the end of a c-string is automatically appended to s after the data extracted. The number of characters read by this function can be obtained by calling to the member function gcount. A global function with the same name exists in header. This global function provides a similar behavior, but with standard C++ string objects instead of c-strings: see getline(string). Parameters s A pointer to an array of characters where the string is stored as a c-string. n Maximum number of characters to store (including the terminating null character).

31 Tekstitiedostosta lukeminen tMyn31 This is an integer value of type streamsize. If the function stops reading because this size is reached, the failbit internal flag is set. delim The delimiting character. The operation of extracting succesive characters is stopped when this character is read. This parameter is optional, if not specified the function considers '\n' (a newline character) to be the delimiting character. Return value The function returns *this. Errors are signaled by modifying the internal state flags:

32 Tekstitiedostosta lukeminen tMyn32 flagerror eofbitThe end of the source of characters is reached during its operations. failbitNo characters were extracted because the end was prematurely found. This is also set if the function stops extracting because n-1 characters were extracted (n including the terminating null-character). Notice that some eofbit cases will also set failbit. badbitAn error other than the above happened. Additionaly, in any of these cases, if the appropriate flag has been set with member function ios::exceptions, an exception of type ios_base::failure is thrown.

33 Tekstitiedostosta lukeminen tMyn33 Seuraavassa esimerkissä luetaan näytölle tiedostoon tallennettu teksti käyttäen syöttöfunktiota int get(). Tiedoston sisältö on seuraavanlainen:

34 Tekstitiedostosta lukeminen tMyn34 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const char* tiedNimi="d:\\data\\emailit\\roskaa3.txt"; ifstream taaltaLuetaan(tiedNimi); if (!taaltaLuetaan)

35 Tekstitiedostosta lukeminen tMyn35 { cout<<"Tiedoston "<<tiedNimi <<" avaus ep\204onnistui!"; exit(1); } char merkki; while(!taaltaLuetaan.eof()) { taaltaLuetaan.get(merkki); if(merkki=='ä') cout<<"\204"; else if(merkki=='ö') cout<<"\224"; else cout<<merkki; } return 0; }

36 Tekstitiedostosta lukeminen tMyn36 Näytölle tulostuu tyylikkäästi:

37 Tekstitiedostosta lukeminen tMyn37 Kokeillaan jäsenfunktiota istream& getline (char* s, streamsize n, char delim ) Ensimmäisenä parametrina annetaan tieto siitä minne tiedostosta luettu ”rivi” tallennetaan. Toisena parametrina on maksimimäärä luettaville merkkivakioille – jos 1. parametrina on char- tyyppinen taulukko, jonka koko on k, niin sitten 2. parametrin koko on k. Kolmantena parametrina on merkkivakio, joka lopettaa merkkivakioiden lukemisen tiedostosta. Oletusarvona on rivinvaihto ’\n’.

38 Tekstitiedostosta lukeminen tMyn38 Olkoot tiedostossa tietoja henkilöistä: nimi, katuosoite ja postitoimipaikka. Kukin tieto päättyy $-merkkiin: Järjestetään tulostus näytölle siten, että kukin ”kenttä” on omana rivinään:

39 Tekstitiedostosta lukeminen tMyn39 #include "stdafx.h" #include using namespace System; using namespace std; int main(array ^args) { const int koko=80; char neTiedot[koko]; const char* tiedNimi="d:\\data\\emailit\\roskaa4a.txt"; fstream taaltaLuetaan(tiedNimi, ios::in); if (!taaltaLuetaan) { cout<<"Tiedoston "<<tiedNimi <<" avaus ep\204onnistui!"; exit(1); }

40 Tekstitiedostosta lukeminen tMyn40 taaltaLuetaan.getline(neTiedot, koko, '$'); while(!taaltaLuetaan.eof()) { cout<<neTiedot<<endl; taaltaLuetaan.getline(neTiedot, koko, '$'); } taaltaLuetaan.close(); return 0; }

41 Tekstitiedostosta lukeminen tMyn41 Tulostuksesta tulee selkeämpi, kun tiedostoon lisätään rivinvaihto kunkin henkilön tietojen jälkeen. Silloin näytölle tulostuu ylimääräinen rivi. Ohjelmaan ei siis tule mitään muutosta:

42 Tekstitiedostosta lukeminen tMyn42 Nyt tulostuu:

43 Tekstitiedostosta lukeminen tMyn43 Vielä on jäljellä pieni kauneusvirhe: skandimerkit eivät tulostu kunnolla näytölle. Tehdään pieni muutos ohjelmaan:

44 Tekstitiedostosta lukeminen tMyn44 … while(!taaltaLuetaan.eof()) { int i=0; while(neTiedot[i]!='\0') { if(neTiedot[i]=='ä') cout<<"\204"; else if(neTiedot[i]=='ö') cout<<"\224"; else cout<<neTiedot[i]; i++; } cout<<endl; taaltaLuetaan.getline(neTiedot, koko, '$'); } …

45 Tekstitiedostosta lukeminen tMyn45


Lataa ppt "Tekstitiedostosta lukeminen tMyn1 Tekstitiedostosta lukeminen Tiedosto voidaan avata pelkästään lukemista varten tai kirjoittamista ja lukemista varten."

Samankaltaiset esitykset


Iklan oleh Google