0% found this document useful (0 votes)
23 views11 pages

FILES (Module-5)

The document provides an overview of file handling in C programming, detailing the standard streams (stdin, stdout, stderr) and the process of declaring, opening, processing, and closing files. It explains the differences between text and binary files, the use of file pointers, and the various modes for opening files. Additionally, it covers functions for reading data from files, including fscanf, fgets, and fgetc.

Uploaded by

donfan734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views11 pages

FILES (Module-5)

The document provides an overview of file handling in C programming, detailing the standard streams (stdin, stdout, stderr) and the process of declaring, opening, processing, and closing files. It explains the differences between text and binary files, the use of file pointers, and the various modes for opening files. Additionally, it covers functions for reading data from files, including fscanf, fgets, and fgetc.

Uploaded by

donfan734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
A tty ty a _colledtitn of aber dont shoroge lamin: Li 3 shandard streams stdin 5 std ty pu stdout —> shi ouput Stdere —s std enor std caput (stdin SURE nee Docoisrey, i clade pen Using ‘read’ opexetion Std_oukpt Cstdlout) skh outpk & the Shream: aha 0 vO veritrs ha olp dota . pr O% ann Uneng Cade! qusedion / PAGE:.,. DATE (sid ervox (sider) = Bal —ausouitid with Au she When aS Linked “Beg creaked a baker is auco moth! cally a amoustid with Ine Shroom . Tech ond [ale eo Wad Sang Sead ne borngorauns sissy of dats Ml” an da be Pram eh stint "a, Ble Bulfer act, os am interface Tae eee and dure borders Data fom trogion |e [Bete J ——_> so fe nalfa —_ 7 hate Similowly, fr deodeng Bota Crm a hi = Tyfes of File “O ASC tect fits @ Birany Bis ASCH tex files Atel Bl, O Shean of dhowattns phat con ke pov lag procemed ley a _usmouiin by focwound ireckion . A bod filo opened far only oma bind of ion _( reading voring , Aprende) oh any a Sparen Sine —— ~ Ey Bnonug Files ; tue f dotla A buvany file may conto OST gt + ‘wrage | Computer Fundamentals and Programming in C In a text file, an integer value 123 will be stored as a sequence of three characters—1, 2, and 3. Socach cha will take I byte and, therefore, to store the integer v 123 we need 3 bytes. However, yy file, the int value 123 ary form. This clearly indicates that binary files take less space to store the same piece of data and eliminate conversion between internal and external representations and are thus more efficient than the text files. GB usING FILEs INC To use files in C, we must follow the steps given below: + declare a file pointer variable + open the file + process the file * close the file In this section, we will go through all these steps in de 16.2.1 Declaring a File iter Variable There can be a number of files on the disk. In order to access aparticular file, you must specify the name of the file that has tobe used. Thisis accomplished Programming Tip: by using a file pointer variable An error will be that points to a structure FILE generatedifyou | (defined in stdio.h). The file Use the filenameto pointer will then be used in all faccessafilerather | subsequent operations in the [than thefilepointer, | file. The syntax for dectaring a file pointer is. FILE *file_pointer_nane; For example, if we write FILE *fp3 ‘Then, fp is declared as a file pointer. 46.2.2 Opening a File ‘A file must first be opened before data can be read from it or written to it, In order to open a file and associate it with 2 stream, the fopen() function is used. The prototype of fopen() can be given as FILE *fopen(const char *file_name, mode); Using the above declaration, the file whose pathname is the string pointed to by fie_nane is opened in the mode specified using the mode, If successful, fopen() returns a pointer- to-structure and if it fails, it returns NULL. const char File Name Every file on the disk has a name associat aming convention of a file varies from aM The system to another, For example, in DOS qe CPting have one 10 eight charters optionally fe ie nme lowed period and an extension that has one to three However, Windows and UNIX permit fi maximum of 256 characters. Wi restrictions on usage of certain ch i.c., characters such as /,\, 25%, 2," part of a file name. In, fopen() may contain the path infor ; tioning of specifying the filename. The path gives informs! about the location of the file on the disk, If fem lename is specified without a path, it is assumed that the fle located in the current working directory. For example, fy file named Student .0AT is located on D drive in director cA, then the path of the file can be specified by writing D:\BcA\student.DAT In C, a backslash character has a special meaning with respect to eseape sequences when placed in a string, Soin order to represent a backslash character in a C program, ‘you must precede it with another backslash, Hence, the above path will be specified as given below in the C program. D:\\BCA\\ Student .DAT File Mode ‘The second argument in fopen() is the mode, Mode conveys to C the type of processing that will be done with the file. The different modes in which a file can be opened for processing are given in Table 16.1. Look at the code given below which opens a file using fopen(). FILE *#p3 fp = fopen("Student.DAT", “r"); printf("\n The file could not be opened”); exit(1)3 y OR char filenane[30]; FILE *fp3 gets(filenane) ; fp = fopen(filenane, Sf (Fp==NULL) re! printf("\n The file could not be opened"); exit(1)5 File modes ==: Awl | Description sibjebs | Createa binary fileforread/write. | [ssbiaby [Append a binary fle forreadiwrie, ss) [=revape il [Append w binstyjfle fected rite aaa) [Open a ext HIS TorreNIn Ir ne TaeaRTaISyuEeT| ‘Oren fest RTs Toe realng: IF HE RRC UTS) WORT sedi hen an enor eee [Opens text efor wn. tre rican aasrnor lst then itisereated. Ith Ms kee ee its contents would be deleted. om Append to a text file, Ifthe file does not exist his | re loos not exist Is Open a binary file for reading. "indicates Binary | By deft hs Wl es sequential en eda Format ‘Open a binary file for writing. ‘Append to a binary file. cael Open a text file for both reading and writing. The stream will be positioned atthe beginning ofthe Be. When you specify you indicate that you vant to read the fle before you write to it. Thus, the fle must already exist. ‘Open a text file for both reading and writing The stream will be ereated if it does not exist, and wl be ‘Open a tet file for both reading and weiing Th S| ‘stream Will be positioned at the end of the file content. We have already discussed that fopen() returns a pointer to FILE structure if successful and a NULL otherwise. So itis ‘to opena file that recommended to check whether Programming Tip: the file was successfully opened ‘Anerror will be before actually using the file. generated if you try The fopen() function can fail to open the specified file under certain conditions that are listed as follows: + Opening a file that is not ready for use ; + Opening a file that is specified to be on a non-existent directory/drive ; + Opening a non-existent file for reading + Opening a file to which access is not permitted 16.2.3 Closing a File Using fclose() To close an open file, the fclose() function is used which disconnects a file pointer from a file. After fclose() has disconnected the file pointer from the file, the pointer can be used to access a different file or the same file but in a different mode. The fclose() function not only closes the file, but also flushes all the buffers that are maintained for that file, If you do not close a file after using it, the system closes it automatically when the program exits. However, Since there is a limit on the number of files which can be , Nhat th Icon Wee \ ee {Sheng Here, §p js aoe Which points to 1 © rein oa Pines : has to be closed. ne hat fetus an integer value which indietes seers sunen /as successful or not, A zero is Teturned if the funcnsy ‘Was successful, and a non-zero value is retur 2d i pam vase cneditane les When they are: not golng tobe used {furtherin the program, When fclose()is executed) any unwritten buffered dat) for the stream will be written to the file and any unread. Buffered data will be discarded, Z Inadditionto Fclose(), thereisa function Fcloseall() which closes all the streams that are currently opened except the standard streams (such as stdin, stdout, and stderr). The prototype of fcloseal1() can be given as int fcloseall (void); fcloseal1() also flushes any stream buffers and returns the number of streams closed. Ifa file’s buffer has to be flushed without closing it then, use #flush() of flusha11() to flush the buffers of all open streams. (GB_ READING DATA FROM FILES C provides the following set of functions to read data from afile. + fscanf() + fgets() + feetc() * fread() In this section, we will read about these functions. 16.3.1 fscanf() ‘The fscanf() function is used to read formatted data from the stream. The syntax of fscanf() can be given as int fscanf(FILE ‘stream, const char *format,-); ‘The ¢scanf() function is used to rend data from the stream and store them according to the parameter format into the Tocations pointed by the additional arguments, Howey, these additional arguments must point to the objects It have already occupied memory. These objects are ot (WPS as specified by their corresponding format tag wi format string. 438 Similar to the format specifi in fscan¢() also the format speci : se vith a percentage sign (%). The format specifier pear specify the type and format of the data that has tobe obtained from the stream and stored in the memory Iecntions pointed by the additional arguments. THe prototype of a format specifier can be given aS x{+] [width] [modifiers}type, where «+ is an optional argument that suppresses assignment of the input field. It indicates that data should be read from the stream and ignored (not stored in the memory location). wvideh specifies the maximum number of characters to be fead. However, fewer characters will be read if the scan function encounters a white space or an unconver character. modifiers can be hy ‘Computer Fundamentals and Progr fers used in scanf(), ifiers is a C string that 1, of L for the data pointed by the corresponding additional arguments. Modifier h is used for short int or unsigned short int, 1is used for long int, unsigned long int, or double values. Finally, t is used for long double data values. .pe specifies the type of data that has to be read. It also indicates how this data is expected to be read from the jers for fscanf function are given in "for single character ~ for decimal values. for floating point numbers for octal numbers fora sequence of string of characters The fscanf function has some additional arguments. Each of the additional arguments must point to an object of the type specified by its corresponding % tag within the format string, in the same order. “The Fscant functions similar to the scant function, | except that the first argument of fscanf specifies | stream from which to read, whereas scanf can only read_ | from standard input aid Let us look at an example which illustrates the use of fscanf(). Here, we will not give the complete program but just a partal program 10 demonstrate the use of ‘scanf() : yngin winclude int main() { FILE *fp5 char name[80]5 int roll_nos fp = fopen("student.DAT", “r AF (Fp==NULL) printf("\n The file could not be opened”); exit(1)5 } printf("\n Enter the name and roll nunbep of the student: "); 1/ READ FROM KEYBOARD Fscanf(stdin, "Ks %d", name, &roll_no); 7+ read fron keyboard */ prinee(*\n NAME: %s \t ROLL NUMBER = xr name, roll_no); // READ FROM FILE Student-DAT Fscant(fp, "Bs ¥d", name, &roll_no); printf("\n NAHE: %s_\t ROLL NUMBER = x4", name, roll_no); Fclose(fp)3 return 05 > Output Enter the name and roll number of the student: 1 Zubin aMle: Zubin ROLL NUMBER = 01 NAME: Goransh ROLL NUMBER = 03 “then specify stdout instead of specify pointer. aidig ees 16.3.2 fgets() ‘The fgets() function stands for file ger string, The Feets() function is used to get a string from a stream. The syntax of fgets() can be given as char *fgets(char *str, int size, FILE stream); ‘The fgets() function reads at most one less than the number of characters specified by size (gets siz@, = characters) from the given stream and stores them 19 the string str. The fgets() fuction terminates #5 500” 30 encounters either a newline character, EOF, oF any ON! error, However, if a newline character is encountered it is retained. When all the characters are read without 2 error, "\O" characteris appended tothe end of the site it 5() encounters newline character, it does ¢ not retain it ¢haracter (if any) is not stored in the strings” ‘"® B&Wline ‘On successful completion, fgets() will retu str However, if the stream is at EOF, the EOF in ‘ream will be set and fgets() will return in case, fgets() encounters any error whi ‘rror indicator for the stream will be set a will be returned. Look at the program c which demonstrates the use of fgets(). #include int. main() { FILE *fp3 char str[80]; fp = fopen("ABC.DAT", if (Fp==NULL) { \dicator for the |@ NULL pointer, ile reading, the ind NULL pointer ‘ode given below printf("\n The file could n " pa le could not be opened"); z /* the file will read 79 characters during each iteration and will print them on the screen */ while (fgets(str, 80, fp) I= NULL) printf("\n %s", str); printf("\n\n File Read. Now closing the file"); fclose(fp)5 return 03 } Output Abdceweeferrttet gfejjherroiew tjketjer fddfgdfefd File Read. Now closing the file 16.3.3 fgets() The fgetc() function returns the next character from stream, EOF if the end of file is reached, or if there is an error. The syntax of fgetc() can be given as int fgetc(FILE *stream); fgetc() returns the character read as an int or returns EOF to indicate an error or end of file. fgetc() reads a single character from the current positon of a file (file associated with stream). After reading the character, the function increments the associated file pointer (if defined) to point to the next character. However, ifthe stream has already reached the end of file, the E0F indicator for the stream is set Look Ef the following program code which demonstrates the use o feets() function. include main() FILE «fp; : char str(go}; int 4, ch; £ = fopen(“Progr: Foray =e Préntf("\n The file cout opened”); exit(a); not be // Read 79 characters and s oni, Fatt): coat (1 € 79) 88 (FeoF(Fp) == 0); 44) str[i] = (char)ch; ch = fgetc(strean) ; // reads character by character tore them in str } str[i] = ‘\o'; 1/ append the string with a null character printf("\n %s", str); fclose(fp); } ‘The above program displays either first 79 characters or less characters if the file contains less than 79 characters. ‘The Feof() function is used to detect the end of file. We will read more on this function later in this chapter. 16.3.4 fread() The fread() function is used to read data from a file. Its syntax can be given as int fread(void *str, size t size, size t num, FILE *stream); ‘The fread() function reads num number of objects (where each object is size bytes) and places them into the array pointed to by str. The data is read from the given input stream. ‘Upon successful completion, fread() returns the number of bytes successfully read. The number of objects will be less than num if a read error or end-of-file is encountered. If size or num is 0, fread() will return 0 ‘and the contents of str and the state of the stream remain ‘unchanged. In case of error, the error indicator for the stream will be set. ‘The fread() function advances the file position indicator for the stream by the number of bytes read. @) Computer Fundamentals and Programming in C es the Look at the program given below which ilk use of fread), include printf("\n The file could not be opened"); exit(1); } fread(str, 1, 10, fp); 7+ In the str 10 objects of 1 byte are read from the file pointd by fp */ str[10]= "\0"; printf(*\n First 9 characters of the file are: %s", str); fclose(fp); + Output . First 9 characters of the file are: Hello how Since fread() returns the number of bytes successfully read, we can also modify the above program to print the number of bytes read. This would be helpful to know how many characters were read. #include main() t FILE *Fp3 char str[80]; size_t bytes_read; fp = fopen("Letter.TxT", “r+"); if (Fpe=NULL) { printf("\n The file could not be opened"); exit(1); + bytes_read = fread(str, 1, 79, fp); str[bytes_read+1]= '\0'; /* explicitly store null character at the end of str */ printf("\n First %d characters of the file are: %s", bytes_read, str Felose(fp); y The output will depend on the contents of the file. Assuming 14 characters were read, the output can be given as Hello how ru? This program assumes that you have created a file Letter. TAT that contains 14 characters which have been displayed above. The fread() function does not check for overflow in the receiving area of memory. It is the programmer's job to ensure that the memory pointed to by str m - enough to hold the number of objects being reag. °° If you have opened a stream for updating and later you want to switch from reading to writing ory, You must fist use the fseek() or reningc) However, if you have been reading and have ye end-of-file, then you can immediately switch ro sain() { FILE *#p3 int 45 char name(20]; float salary; fp = fopen("Details.TxT", “W"); print#("\n The file could not be opened”); enst(1)5 B [ian the arguments ashore ant ocunsigned shor’ Sint é Fen he argument is atong ant orunsiened Tore int for integer specifiers : 46.4.2 fputs() | When ibe arumentisatong| double (osed for, ‘ . ioating point pecifiers)| Pe The opposite of fgets() is puts (). The fputs() function jg used to write a line to a file. The syntax of fputs() can be given as int fputs(const char «str, FILE «stream); ‘The fputs() function writes the string pointed to by str to the stream pointed to by stream, On successful completion, fputs() returns 0. In case of any error, fputs() returns EOF. ttinclude main() { FILE *#p3 char feedback[100]; fp = fopen("Conments.TxT", “W")3 if (fp==NULL) 4 prantf(“\n The fle could not be opened"); exit(a)s ) printf(*\n Provide feedback on this book: gets (Feedback); Ffush(stdin); U/ Feedback stored fputs(feedback, fp); Felose(fp); } Output Provide feedback on this book: good 16.4.3 fputc() ‘The fputc() function is just the opposite of Fgetc() and is used to write a character to the stream. int fpute(int c, FILE *strean); ‘The fputc() function will write the byte specified by C (converted to an unsigned char) to the output stream Pointed to by stream. On successful completion, fputc() will return the value it has written. Otherwise, in case of error, the function will return EOF and the error indicator for the stream will be set. #include main() t FILE ~fp; char feedback[100); int i; fp = fopen( "Comments. TXT i#(fp==NULL) { printf("\n The file could not be opened”); exit(1)5 "Ys } printf("\n Provide feedback on this book: “); gets(feedback); for(i = 031 « feedback[i];i++) fpute(feedback[i], fp); felose(fp); When an ouy is unbuffered, appears onthe device a soon aa ll writen, When itis buttyel characters are saved imemegt and then written out sa group. th order vo fore bua characters to be output before the buffer iy full ed Ffush(), PUL stream information ‘estination “and has a value = 16.4.4 furite() The furdte() function is used to write data toa fle, The syntax of furite can be given as int furite(const void *str, sizet size, size_t count, FILE *strean); ‘The fwrite() function will write objects (number of objects will be specified by count) of size specified by size, from the array pointed to by str to the stream pointed to by stream. The file-position indicator for the stream (if defined) will be advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file. position indicator for the stream is unspecified. On successful completion, the furite() function returns the number of objects successfully written, The number of objects will be less than count if an error encountered. If size or count is 0, furite() will return © and the contents of the stream remains unchanged In case of error, the error indicator for the stream will be set, #include #include Winclude int main(void) { FILE *fp; size_t count; char str[] = "GOOD MORNING"; fp = fopen("Welcome.txt", “wb"); if (Fp=NULL) { printf("\n The file could not be opened” exit(1); } count = furite(str, 1, strlen(str), fp) printf("\n Xd bytes were written to the file", count); Felose(fp); return 0; ) Output 13 bytes wore written to the file Parice() can be Used to WOE frvctures to file However, fart with fles that are opened In bin ters) Integers) or can be used only mode, (G9) DETECTING THE END-oF FILE STR END-OF-FILE when re ling or writing data to files, we oft {aavtly how long the file is, For example, white seen te ie, we usally start reading from the beginning nd oceed towards the end of the file, I: iis to detect EO} in C, there are two | While reading the file in text: m character, the programmer can co; that has been read with EOF, which j defined in stdio.h with statement does that ‘ode, character by mpare the character is a symbolic constant @ value -1, The following while(2) { c= feetc(fp); J/ here c is an int variable if (ce=EOF) break; printf("Xe", ¢)5 } + The other way is to use the standard library function feof() which is defined in stdio.h. The feof() function is used to distinguish between two cases: 1 When a stream operation has reached the end of a file ‘When the EOF error code has returned an error indicator even when the end of the file has not been reached ‘The prototype of feof() can be given as int feof(FILE *fp); ‘The function takes a pointer to the FILE structure of the stream to check as an argument and returns zero (false) when the end of file has not been reached and a one (true) if the end of file has been reached. Look at the following: ‘The output assumes that a file Student.DAT already exists and conatins the following data: 1 Aditya 2 Chaitanya 3 Goransh #include nain() { FILE +p; char str[80]; fp = fopen("Student.DAT", "r")3 if (fp==NULL) { print#("\n The file could not be opened"); exit(ay; , Foy ~S /* The oop continues un the end-of-fle +/ while( 1 FeoF(fp)) { fgets(str, 79, fp); 11 Reads 79 bytes at a tine printf("\n Xs", str); AL FD reach y printf("\n\n File Read. Now closing the file"); ene fclose(fp); return 0; ? Output 1 Aditya 2 Chaitanya3 Goransh ERROR HANDLING DURING FILE OPERATIONS tis quite common that an error may occur while reading data from or writing data to a file. For example, an error may arise when trying to read a file beyond EOF indicator when trying to read a file that does not exist when trying to use a file that has not been opened when tying to use a file in an inappropriate mode, i.e., writing data to a file that has been opened for reading when writing to a file that is write-protected (i.., trying to write to a read-only file) If we fail to check for errors, then the program may behave abnormally. Therefore, an unchecked error may result in premature termination ‘of the program or incorrect output. In C, the library function ferror() is used to check for errors in the stream. Its prototype can be given as int ferror (FILE *stream); Programming Tip: An error will be generated if you try toreadafile that is opened in w mode and vice versa, ‘The ferror() function checks for any errors in the stream. It retums value zero if no errors have occurred and a non-zero value if there is an error. The error indication will last until the file is closed or it is cleared by the clearerr() function. Look at the code given below which uses the ferror(). winclude main() {

You might also like